vue.js - 创建组件后如何在 Vuejs 中运行函数?
问题描述
我创建了一个组件,该组件具有进行外部 API 调用然后填充数组的功能。我第一次使用created() life hook 运行该函数。我将一个变量从父组件传递到该组件,然后基于此变量更改,我希望该函数再次运行。我如何做到这一点。
在下面附上我的代码
<template>
<div>
<p>{{ data_to_show_on_mainpage }}</p>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'GetCategoryItemsAndDisplayOne',
props: ['categoriesfordisplay','ismainpage', 'catalogselected'],
data(){
return {
IsMainPage_1 : "",
data_to_show_on_mainpage : [],
}
},
watch: {
catalogselected: function(){
this.GetItemsToShowonMainPage()
}
},
methods:{
changevalue(){
console.log("i am reducing it to emplty after change of catalog")
this.IsMainPage_1 = this.catalogselected
this.data_to_show_on_mainpage = []
},
CatlogService(catlog_name,category,gender,mainpage){
let url = "http://localhost:5000/xyz/" + (this.catalogselected).replace(/'/g,"%27") +"/api/"+ (gender) + "/catalogvis/" + (category) +"/items"
console.log(encodeURI(url))
axios.get(encodeURI(url)).then((resp)=>{
this.data_to_show_on_mainpage.push(resp.data.response.Results.results[0])
})
.catch(err => {
console.log("we got an error the url is " + url)
console.log(err);
})
},
GetItemsToShowonMainPage(){
this.changevalue()
if(this.categoriesfordisplay.men_for_display.length>0){
for(let i =0;i<this.categoriesfordisplay.men_for_display.length;i++){
let category = this.categoriesfordisplay.men_for_display[i].replace(/"/g,"%27");
this.CatlogService(this.catalogselected,category,'men',this.ismainpage)
}
}
if(this.categoriesfordisplay.women_for_display.length>0){
for(let i = 0;i<this.categoriesfordisplay.women_for_display.length;i++){
let category = this.categoriesfordisplay.women_for_display[i].replace(/"/g,"");
this.CatlogService(this.catalogselected,category,'women',this.ismainpage)
}
}
},
},
created(){
this.GetItemsToShowonMainPage()
}
}
</script>
<style>
</style>
每当更改catalogselected变量时,我如何触发GetItemsToShowonMainPage()函数。
解决方案
看起来不错。正如@a-lau 所说,确保父母正在更新catalogselected
道具
顺便说一句,你可以这样写你的观察者并完全删除created
钩子:
watch: {
catalogselected: {
handler: "GetItemsToShowonMainPage",
immediate: true
}
}
如果你仍然有问题,你可能想在https://codesandbox.io/s/vue上写一个最小的复制品
推荐阅读
- java - 斑马扫描仪服务
- javascript - JavaScript 中电话号码验证的正则表达式
- sql - SQL中的union和union all有什么区别?
- azure - 就应用程序洞察数据而言,“信息”究竟是什么?
- javascript - 简单的手风琴不起作用,因为处理程序一次触发 2 次
- react-native - NativeBase 中的仅图标按钮
- opencl - 在 Windows 中使用 github 操作的 OpenCl
- javascript - 用于解包数组的 JavaScript 循环缓慢(> 两分钟)
- reactjs - 如何使用下拉选项控制反应表的页面大小
- node.js - 电子生成器自定义 NSIS 包含脚本宏不起作用