there is a primitive vue.js widget, which consists of two pages. In each page you can select dummy options from dropdown (which change value1 and value2 variables accordingly)
The problem is when I move from “stepOne” to “stepTwo”, for some reason the value of value2 becomes undefined unexpectedly (even though there is no logical connection between value1 and value2, nor step variable).
Ideally, after the first step, in second step it should automatically select “option 1”, as the value equals to value2=1
I wonder why undefined is assigned to value2, and how can I prevent the given behavior
Here is my sample code, that contains this weird behavior:
<div>
<div id=”app”>
<div v-if=”step === steps.stepOne”>
<p>This is step One</p>
<select v-model=”value1”>
<option v-for=”item in array1” :value=”item.value”>{ item.name }</option>
</select>
<button @click=”changeStep()”>Next</button>
</div>
<div v-if=”step === steps.stepTwo”>
<p>This is step Two</p>
<select v-model=”value2”>
<option value=”2”>option 2</option>
<option value=”0”>option 0</option>
<option value=”1”>option 1</option>
</select>
</div>
value1: {value1}
<br>
value2: {value2}
</div>
</div>
<script src=”https://cdn.jsdelivr.net/npm/vue"></script>
<script>
var steps = {
stepOne: 1,
stepTwo: 2,
};
var app = new Vue({
el: ‘#app’,
data: {
step: steps.stepOne,
value1: ‘b’,
value2: 1,
array1: [
{
name: ‘option a’,
value: ‘a’,
},
{
name: ‘option b’,
value: ‘b’,
},
]
},
methods: {
changeStep() {
this.step = steps.stepTwo;
}
},
watch: {
value1: function(newValue) {
console.log(“value1: “ + newValue);
},
value2: function(newValue) {
console.log(“value2: “ + newValue);
}
},
});
</script>
Solution :
there is no idea about how vue.js works, but I’ve tried putting a : before the value attribute and it started working!
<div>
<div id=”app”>
<div v-if=”step === steps.stepOne”>
<p>This is step One</p>
<select v-model=”value1”>
<option v-for=”item in array1” :value=”item.value”>{ item.name }</option>
</select>
<button @click=”changeStep()”>Next</button>
</div>
<div v-if=”step === steps.stepTwo”>
<p>This is step Two</p>
<select v-model=”value2”>
<option :value=”2”>option 2</option>
<option :value=”0”>option 0</option>
<option :value=”1”>option 1</option>
</select>
</div>
value1: {value1}
<br>
value2: {value2}
</div>
</div>
<script src=”https://cdn.jsdelivr.net/npm/vue"></script>
<script>
var steps = {
stepOne: 1,
stepTwo: 2,
};
var app = new Vue({
el: ‘#app’,
data: {
step: steps.stepOne,
value1: ‘b’,
value2: 1,
array1: [
{
name: ‘option a’,
value: ‘a’,
},
{
name: ‘option b’,
value: ‘b’,
},
]
},
methods: {
changeStep() {
this.step = steps.stepTwo;
}
},
watch: {
value1: function(newValue) {
console.log(“value1: “ + newValue);
},
value2: function(newValue) {
console.log(“value2: “ + newValue);
}
},
});
</script>