vuejs2 - 再次更改值而不触发手表
问题描述
我试图找到一种解决方法来解决在相同属性的手表内更改 2 向绑定的问题,避免再次调用手表。例如:
<select v-model="language">
<option ... />
</select>
watch:{
language(newVal // 'fr' , oldVal // 'en'){
if(condition){
// do something
} else {
// roll back to the old language
this.language = "en" // will call watch again.
// Looking for something like this:
// Vue.set(this, 'language', 'en', { watch: false })
}
}
}
我考虑过使用@change
,但这无济于事,因为我必须使用对象而不是普通值再次设置值。
我知道我可以使用其他 2-way 属性并将其用作标志,但我寻找更优雅的东西。
解决方案
为什么首先回滚用户的选择?您可以使用 acomputed property
提供有效选项的过滤列表,以提供更好的用户体验。
下面的示例仅允许您选择en
条件复选框是否为真。
Vue.config.productionTip = false;
new Vue({
el: '#app',
template: `
<div>
<p>Condition: <input type="checkbox" v-model="condition" /></p>
<p>Selection: {{selection}}</p>
<select v-model="selection">
<option v-for="opt in filteredOptions" :key="opt.value" :value="opt.value">{{opt.label}}</option>
</select>
</div>
`,
data: () => ({
selection: undefined,
condition: true,
options: [
{ label: 'English', value: 'en' },
{ label: 'French', value: 'fr' },
{ label: 'Spanish', value: 'es' },
],
}),
computed: {
filteredOptions() {
return this.condition ? this.options.filter(x => x.value === 'en') : this.options;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
推荐阅读
- c# - Blazor 服务器:
我有一系列 3 个 InputSelects,第二个通过 SQL 查询从第一个级联。当通过 oninput 事件选择第一个下拉列表时,我有额外的逻辑运行。(我知道 onchange 和 bind-Value 不能在同一个元素上声明)。
选择第一个后,我的值将填充
- c++ - 试图对结构进行排序但它不起作用?
- php - 如何将 Laravel 数据表(yajra)添加到现有项目中?
- c# - 如何避免在 foreach 循环之前对关联/组合/聚合对象的层次结构进行许多空检查?
- windows - GetActiveProcessorCount 和 GetMaximumProcessorCount 有什么区别?
- php - 使用 XAMPP 连接到数据库
- php - 在 PHP 中包含文本并在没有值时隐藏它
- amazon-web-services - 如何将 bucket-owner-full-control 分配给 s3 存储桶中的数百万个现有文件?
- r - 从状态组创建区域经纬度数据框
- java - Webview 视频 (iframe) 不播放,除了声音被静音