我有一个原始的Vue小部件,它由两个页面组成。在每个页面中,您都可以从下拉菜单中选择虚拟选项(它们会相应更改value1
和value2
变量)
问题是当我从“ stepOne”移到“ stepTwo”时,由于某种原因,value2
的值意外地变成了undefined
(即使value1
之间没有逻辑联系)和value2
或step
变量)。
理想情况下,第一步之后,第二步应该自动选择“选项1”,因为该值等于value2=1
我想知道为什么将undefined
分配给value2
,以及如何防止给定的行为
这是我的示例代码,其中包含以下奇怪的行为:
<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>
答案 0 :(得分:1)
我不知道vue.js的工作原理,但是我尝试将:
放在value属性之前,它开始起作用!
<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>