首页 > 解决方案 > 创建组件后如何在 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()函数。

标签: vue.jsvuejs2vue-component

解决方案


看起来不错。正如@a-lau 所说,确保父母正在更新catalogselected道具

顺便说一句,你可以这样写你的观察者并完全删除created钩子:

watch: {
  catalogselected: {
    handler: "GetItemsToShowonMainPage",
    immediate: true
  }
}

如果你仍然有问题,你可能想在https://codesandbox.io/s/vue上写一个最小的复制品


推荐阅读