我有一个选择元素
<select id="filter" v-model="filter" @change="changeFilter">
<option value="all">All</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
然后在我的组件中
methods:{
changeFilter(){
var that = this
console.log(that.filter)
// this gives me the value from the last select
// If I then use Jquery
that.filter = window.jQuery('#filter').val()
console.log(that.filter)
// This gives the correct up to date value
}
}
为什么我必须使用Jquery来获取这个元素的最新值? 我认为 Vue.js 应该是响应式的?为什么会落后一格?为什么我被迫使用 jQuery 来获取当前选择的选项?这样做似乎 super 违反直觉?
最佳答案
你的错误是做了双向绑定(bind)加上一个事件。该事件在模型更新时同时触发,因此更改尚未发布。
您最好在这里使用 watch 。
首先,删除事件:
<select id="filter" v-model="filter">
<option value="all">All</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
然后将 watch 放入您的 Vue 对象中:
watch: {
filter: function (val) {
// use val here
}
}
关于javascript - 为什么 Vue.js 落后了一点?为什么需要 jQuery 来获取当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312442/