I'm using Vue.js and would like to
I want to set hint value by variable like this.hint[variableA].variableB = 1
How could I do it
data: {
hint: [{a:0,b:0,c:0},{a:0,b:0,c:0},{a:0,b:0,c:0}],
}
methods: {
selectHint(){
this.setHint(0,a)
},
setHint(i,j){
this.hint[i].j = 1
},
},
CodePudding user response:
Here, hint
is an array of object. To acces one of it's child, you need to access the object at the index i
.
Then, if you want to add a new variable, if you're doing it like this.hint[i].newVariable = 1
where newVariable
isn't already in the object, it won't be reative.
If you want to set reactivity (refresh the dom when this variable is added or change in the future), you can do it by using the Vue.set()
method (see this link for more informations)
Example
here when you press the button, il will add a j
property to the first hint with the value 1
new Vue({
el: '#app',
data: {
hint: [{
a: 0,
b: 0,
c: 0
}, {
a: 0,
b: 0,
c: 0
}, {
a: 0,
b: 0,
c: 0
}],
selectedHint: 0,
text: "",
},
methods: {
setHint() {
Vue.set(this.hint[this.selectedHint], this.text, 1)
this.text = ""
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="(h, index) of hint">
<p :key="index">{{JSON.stringify(h, null, 4)}}</p>
</template>
<input type="text" label="property" v-model="text" />
<select v-model="selectedHint" @change="changeSelectedIndex">
<template v-for="(h, index) of hint">
<option :key="index" :value="index">{{index}} </option>
</template>
</select>
<button @click="setHint">Add </button>
</div>
CodePudding user response:
It can be done with this.hints[i][j]=1
, but that will not be reactive, so you should use this.$set
helper :
this.$set(this.hints, i ,{ [j] : 1,...this.hints[i]})