I want to change watch function value as dynamic when setKeywords Method is triggered.So how Can i change value ?
data(){
return {
keywords:null,
productSearch:null,
}
},
//This is method i created.When this method is triggered.The watch function called productSearch(val) must like productSearch(this.keywords)
methods:{
setKeywords(){
this.keywords='test';
}
},
I want to set val = this.keywords when setKeywords method is triggered.
watch: {
productSearch(val){
fetch("https://api.npms.io/v2/search?q=" val)
.then(response => response.json())
}
}
CodePudding user response:
Put a watch
handler for keywords instead
methods:{
setKeywords(){
this.keywords='test';
},
productSearch(val){
fetch("https://api.npms.io/v2/search?q=" val)
.then(response => response.json())
}
},
watch: {
keywords(newVal, oldVal){
if(newVal !== oldVal) this.productSearch(newVal);
}
}
For more simplicity, if you are triggering the setKeywords()
then no need of watch, you can directly call the productSearch inside that handler
methods:{
setKeywords(){ // Note: this must be a dynamic handler to set new values to `keywords`
this.keywords='test';
this.productSearch(this.keywords);
},
productSearch(val){
fetch("https://api.npms.io/v2/search?q=" val)
.then(response => response.json())
}
}
CodePudding user response:
You can centralize your API call in one method:
methods: {
search(search, keywords) {
productSearch(val){
fetch("https://api.npms.io/v2/search?q=" search)
.then(response => response.json())
},
watch: {
keywords(val) {
this.search(this.productSearch, val);
},
productSearch(val) {
this.search(val, this.keywords);
}
}
}