我正在尝试使用 watch
更改使用 vuejs 选择的 select
选项。
这是我的选择:
<option v-for="option in options" v-bind:value="option._id" :id="option.iso">
{{ option.name }}
</option>
我的 watch 功能可以在数据selectedValue
更改时更改值
watch: {
selectedValue: function() {
console.log(document.getElementById(this.selectedValue))
document.getElementById(this.selectedValue).selected = "selected"
},
...
}
它获取了正确的元素。
我也尝试过使用 selected = true
也不起作用。
所选
未应用于该选项...
最佳答案
如果您想在选择更改时处理选项值,可以为选择声明 @change 事件:
<select v-model="selectedValue" @change="onSelectChange(selectedValue)">
<option v-for="option in options" :value="option.value">
{{option.value}}
</option>
</select>
在事件处理程序中,您可以通过 this
处理选定的值或将值直接传递给方法。我更喜欢第二个,它可以使逻辑更清晰,并且仅在上下文中工作,而无需考虑所有数据变量。
data() {
const options= [{
value: 100,
},{
value: 101,
},{
value: 102,
}];
return {
options,
selectedValue: null,
};
},
methods: {
onSelectChange(value) {
// here you can handle a new value and set what you want, e.g.:
const newValue = this.options[0].value;
this.selectedValue = newValue;
},
}
您可以运行此https://jsfiddle.net/igtulm/swj1u52x/3/
附注请不要使用 document.getElementById()
等绕过 Vue 来修改元素状态,这不是正确的使用方法。
关于javascript - 将选项设置为选定的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679525/