Dynamic properties in vue 2

1

I'm studying reactive frameworks for a project, and one of the features I need is to create dynamic properties, in angularJs just start a ng-model that the property was created, but I see that this is not possible in Vue 2 , Because ? is there another way to do this or another current framework that allows this?

    
asked by anonymous 23.10.2017 / 13:54

2 answers

1

To create dynamic variables, you could do the following:

1 - Criar uma variáveis que receberá as variáveis dinâmicas
2 - Fazer um loop para exibi-las
3 - Utilizar this.$set e this.$delete para criar e removê-las

Following is an example code.

new Vue({
  el: "#app",
  data: function() {
    return {
      variaveis: {}
    };
  },
  beforeMount: function() {
    this.add();
  },
  methods: {
    add: function() {
      this.$set(this.variaveis, 'campo1', {
        nome: 'Campo 01',
        valor: 'Valor 01'
      });
    },
    remover: function(key) {
      this.$delete(this.variaveis, key)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script><divid="app">
  <p>É possível criar as propriedades dinamicamente com o vm.$set.</p>
  <div>
    <div v-for="(variavel, key) in variaveis">
      <label>{{ variavel.nome }}</label>
      <input v-model="variavel.valor" :placeholder="variavel.nome" type="text">
      <button v-on:click="remover(key)">Remover</button>
    </div>
  </div>
  <pre>{{ variaveis }}</pre>
  <button v-if="Object.keys(variaveis).length == 0" v-on:click="add">Add</button>
</div>

Note: I made use of this technique to create a page builder with Vue. The difference is that I have several queries and in the creation of each element I say the type in a property.

    
23.10.2017 / 18:04
1

In Vue as you mentioned it forces you to instantiate the empty property in data .

One solution is to create a reference to the element created in the template with ref . So in the template you can have ref="nome" and then you can use this.$refs.nome.style.color = 'blue';

This can be useful in case of positioning for example but should be avoided to insert HTML to avoid possible attacks.

Example: link

    
23.10.2017 / 15:47