Vue.js中如何在触发setKeywords方法时动态修改watch监听的取值?
实现方案
有两种常用实现方式,可根据你的业务场景选择:
方案1:同步修改触发监听的目标值
watch默认仅在监听的属性值发生变化时触发回调,你只需在setKeywords方法中同步给productSearch赋值,即可触发watch回调,且回调入参就是你设置的keywords值:
methods: { setKeywords(){ this.keywords = 'test'; // 新增赋值逻辑,触发productSearch的监听回调 this.productSearch = this.keywords; } }, watch: { productSearch(val){ fetch("https://api.npms.io/v2/search?q="+val) .then(response => response.json()) } }
适用场景:业务逻辑本身需要
productSearch和keywords保持值同步的场景。
方案2:抽离公共逻辑,两处调用
如果productSearch和keywords不需要保持值同步,可将搜索逻辑抽为独立公共方法,setKeywords和watch中分别调用该方法即可:
methods: { setKeywords(){ this.keywords = 'test'; // 直接调用搜索方法传入keywords this.fetchProduct(this.keywords) }, // 抽离的公共搜索方法 fetchProduct(query){ fetch("https://api.npms.io/v2/search?q="+query) .then(response => response.json()) } }, watch: { productSearch(val){ // 监听触发时同样调用公共方法 this.fetchProduct(val) } }
适用场景:
productSearch和keywords是两个独立变量,仅在触发搜索时存在逻辑关联的场景。
内容的提问来源于stack exchange,提问作者Jwalanta Gautam
相关产品推荐
相关产品推荐

