To create dynamic variables, you could do it this way:
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
Follow an example of 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>
<div id="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 used this technique to create a page with Vue. The difference is that I have several deals and in the creation of each element I say the type in a property.
The Vue has the
v-model, is not similar tong-model? You can better explain the functionality you are looking for?– Sergio
@Sergio, when I start one
v-modelit forces me to instantiate the empty property indata{}, would be able to instantiatev-modeland he create the property if it does not exist, as inangularjs? (my tests went online if you’re talking nonsense)– Felipe Duarte
In fact you must have stated in
data. You can explain what you’re doing, maybe there’s a way "there Vue" to do this...– Sergio
Let’s say I’m creating an element dynamically, like a div, by creating this div I’d like to reference it as property, so that I can move things like style, but individually.
– Felipe Duarte
You can do that with
ref?– Sergio
I didn’t know the ref, I believe it fits my problem, would have to give me an example of use?
– Felipe Duarte
https://jsfiddle.net/Sergio_fiddle/50wL7mdz/71248/
– Sergio
This solves a lot of my problems, thank you! if I wanted to answer...
– Felipe Duarte