如何基于v-select选中条件触发事件,且避免页面加载时自动触发
解决v-select选中ADMIN触发消息但默认值不触发的问题
需求说明:
- v-select绑定
user.type,选中用户类型时同步更新v-model - 仅当用户手动选中ADMIN时触发消息
- 页面加载时若
user.type默认值为ADMIN,不触发消息
修改后的完整代码:
模板部分
<w-v-select v-model="user.type" :options="userTypeOptions" @change="displayMessage" :reduce="option => option.type" :clearable="false" />
脚本部分
export default { data() { return { user: { type: 'DEFAULT' // 初始默认值,若设为'ADMIN'也不会触发消息 } }; }, computed: { userTypeOptions() { return userTypes .map(userType => ({ type: userType, label: this.$t(`model.user.types.${userType}`) })) .sort((a, b) => a.label.localeCompare(b.label)); } }, methods: { displayMessage(selectedType) { // 直接使用传入的选中值,或用this.user.type判断都可以 if (selectedType === 'ADMIN') { console.log('You have clicked on ADMIN'); } } } };
关键说明:
@change事件仅在用户手动操作改变选项时触发,页面初始化设置默认值不会触发该事件,因此天然满足“默认值为ADMIN时不触发消息”的需求- 把选中的类型作为参数传给
displayMessage,比直接读取this.user.type更直观,也能避免异步更新导致的取值偏差 - 如果用户再次选择当前已选中的ADMIN选项,多数v-select组件不会触发
@change事件,因此也不会重复触发消息
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

