【问题标题】:Vue - access props in child componentVue - 访问子组件中的道具
【发布时间】:2019-05-24 06:47:50
【问题描述】:

我有一个 Vue 子组件,它通过 props 从父组件接收数据。我希望它设置“名称”属性的值,如下所示:

<template>
    <input v-model="name" type="text" placeholder="Name" id="name">   <!-- this does not work -->

    {{ this.productdata.name }} <!-- this works -->
    {{ name }} <!-- this DOES NOT work -->
</template>

export default {
        data() {
            return {
                name: this.productdata.name
            }
        },
        props: ['productdata'],
        methods: {
            setProductData()
            {
                this.name = this.productdata.name;
            }
        },
        mounted() {
                // because "name: this.productdata.name" doesn't work I tried to make it like below... No success.
                this.setProductData();
        },
}

我猜这与 Vue 子组件 props 变得反应性有关。 我找到了可行的解决方案,但它一点也不优雅:

mounted() {
            setTimeout(() => {
                this.setProductData();
            }, 2000);
        },

有什么更好的建议吗?

【问题讨论】:

    标签: vuejs2 vue-component


    【解决方案1】:

    您可以尝试为您的 productData 使用观察器,它会在 productData 更改时设置您的名称。当我遇到类似问题时,这对我有用。
    因此添加您的导出默认值

    export defaults {
    ...
      watch: {  
        productdata: function () {
          this.setProductData()
        }  
      },
    ...
    }  
    

    【讨论】:

    • 有效!谢谢!
    【解决方案2】:

    你可以把钩子mounted改成created

    created() {
                this.setProductData();
            }
    

    你也可以使用Computed Properties and Watchers

    computed: {
        name: function () {
          return this.productdata ? this.productdata.name : '';
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 2020-06-15
      • 2020-09-12
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2021-08-09
      相关资源
      最近更新 更多