When I think of Web, I think of simple things, now I started thinking in React. Let start from the very beginning.

The why to use React the people on Facebook already answered, then I will write code!

The minimum code example is the following:

See the Pen dGeyxq by Paulo Diogo (paulodiogo) on CodePen.

This code is very simple, but shows the power of React, and we are rendering an element inside a container in the DOM. The render method will render or update in the element, and you can provide a callback that will be called after the element is rendered or updated.

Reducer:

const emprestimo = (
  state = {
    numeroMeses: new BigNumber(36),
    taxa: new BigNumber(1.82),
    valorPrestacao: new BigNumber(304),
    valorFinanciado: new BigNumber(10000)
  },
  action
) => {
  switch (action.type) {
    case "NUMERO_MESES":
      return { ...state, numeroMeses: action.numeroMeses };
    case "TAXA":
      return { ...state, taxa: action.taxa };
    case "VALOR_PRESTACAO":
      return { ...state, valorPrestacao: action.valorPrestacao };
    case "VALOR_FINANCIADO":
      return { ...state, valorFinanciado: action.valorFinanciado };
    default:
      return state;
  }
};

How to calculate the result values?

Create a selector, using reselect!


const valores = state => state;

const derivados = createSelector(valores, state => {
  ///calculate the total...

  return {
    total: total
  };
});

With the selector we need to conect with the reducers:


const mapStateToProps = state => {
  return {
    derivados: derivados(state)
  };
};

connect(mapStateToProps)(CalculoPrestacao);

To use, just do the normal things:

const {    
    derivados
} = state;

<CalculoPrestacao derivados={derivados} />

<Resultado derivados={this.props.derivados} />
const { createSelector } = Reselect;
const { connect } = ReactRedux;

Documentação

In Vue.js you can use v-model to bind values in your form. That is, when you type the value is changed on the state (input event). When you whant to wait the user get out of the control, you can use the modifier .lazy, then the event change will be used instead.

But the world is cruel and when you use a custom component like Vuetifyjs you need to use a different approach. You need to use :value and @change manually.

Example:


<v-text-field  label="Price"
    :value="price"
    @change="value => price = value">      
</v-text-field>

There are many excelent components to get a masked input when you are using vuejs. But, I could not find one that fill all my requisites.

I have use the following aproach:

I used the string-mask component to format the values; Write the get and set for the value of the input; and Write one method to verify if the value typed is an number.

GET:


    get() {
        const valuePrice = state.price;
        const formatter = new StringMask(state.maskinput, {
            reverse: true
        });
        let result = "";
        if (valuePrice !== "" && valuePrice != null) {
            result = formatter.apply(valuePrice.toString().replace(/[^0-9]/g, ""));
        }
        return result;
    }

SET:

set(value) {
    const formatter = new StringMask(state.mascara, {
        reverse: true
    });

    const normalized = value.replace(/[^0-9]/g, "");

    let result = "";

    if (normalized !== "" && normalized !== null) {
        result = formatter.apply(normalized);
    }

    if (result === "0" || result === "0,00") {
        result = null;
    }

    state.price = result;
}

Verify if is number:


methods: {
    isNumber: function (evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
            evt.preventDefault();;
        } else {
            return true;
        }
    }
},

To use:


@keypress="isNumber($event)"
:value="valor" @input="value => valor = value"

We can add a default value, in my case, I cannot allow a zero value.

When you want to create a component that has dynamic child, that’s a case to use the <slot> There are many other cases, but this one is beautiful.

I needed that the title of a card had a dynamic text based on a certain condition, like: if the application has a context, show the label of the context.

Vue.component("personal-title-card", {
    template: `
    <div>
        <div class="float-left">
            <slot></slot>
        </div>                      
        <div class="float-right">
            <strong></strong>
        </div>
    </div>`,
    computed: {
        ...mapGetters(["contextLabel"])
    }
});

To use is as simple as that:

<personal-title-card>Accumsan massa elementum.</personal-title-card>

According to the documentation:

A <slot> outlet without name implicitly has the name “default”.

You can name a <slot> like:

Vue.component("personal-title-card-2", {
    template: `
    <div>
        <div class="float-left">
            <slot name="text"></slot>
        </div>                      
        <div class="float-right">
            <strong></strong>
        </div>
    </div>`,
    computed: {
        ...mapGetters(["contextLabel"])
    }
});

Again, to use is as simple as that:

<personal-title-card>
  <template v-slot:text>
    Accumsan massa elementum.
  </template>
</personal-title-card>

When you write components in vue you sometimes need some internal data in each component, to handle internal behavior.

Like when I had a problem with formating numeric texts.

The component was rendered correctly, but, the first time the user entered the input the format was lost.

I realized that the $refs was undefined and the format function was called again only when the user typed a value and the event input was fired.

So I added a internal data that was changed when the component was mounted and this behavior disappeared.

First add the data in the component:

data: function () {
    return { mounted: false }
},

And changed the value in mounted method:

mounted() {      
    this.mounted = true;
},

And changed my computed value to check the value of the data:

 computed: {
        awesomeValue: {
            get: function () {


                //HERE I CHECK THE VALUE
                if (!this.mounted) {
                    return;
                }

                //... DO THINGS TO GET VALUE

                return valor;
            },
            set: function (value) {

                //... DO THINGS TO SET VALUE

            }
        },

O ASP MVC é realmente um Deus hoje em dia. É venerado por todos os desenvolvedores .NET e muitos de outros mundos. Sem muitas delongas, qual o objetivo, componentizar com ASP MVC. Para muitos deve ser trivial, mas nunca tinha feito isso. Já havia feito sistemas em ASP MVC, mas não um componente. Com dezenas de possíveis clientes. Aí está uma coisa que a Microsoft faz bem (#FanBoyDetected), componentizar e deixar a nossa vida mais tranquila, não mais fácil.

É muito fácil reusar em ASP MVC. No meu caso, criei uma ‘class library’ e adicionei as referências que eu iria usar (via nuget).

No caso de páginas, scripts, css etc, segue o rito de sempre, criar o que se quer e marcar ele como ‘Embedded Resources’.

Quando for criar as ‘Views’, pode ser criado no mesmo esquema das aplicações padrão:

$(Project)/Views/Controller/Pagina.wtv

Inclusive pode ser criado um arquivo Web.config na pasta ‘Views’ para configurações.

Quanto aos outros tipos de recursos:

Eu estou usando o ‘EmbeddedResourceVirtualPathProvider’ feito pelo @mcintyre321. Ele carrega os arquivos que estiverem em ‘Embedded Resources’.

Install-Package EmbeddedResourceVirtualPathProvider

Vai ser adicionado um arquivo ‘App_Start\RegisterVirtualPathProvider.cs’, que deve ser executado no start da aplicação, no ‘Global.asax’.

Enfim, era isso aí.

PS. Post em construção, vou fazer um projeto de teste.