Vue-子组件中的访问道具

时间:2018-12-25 18:31:27

标签: vuejs2 vue-component

我有一个Vue子组件,该子组件通过props从父级接收数据。我想要它设置“ name”属性的值,如下所示:

<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子组件道具变得反应性有关。 我有最有效的解决方案,但是一点都不优雅:

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

有人建议如何做得更好吗?

2 个答案:

答案 0 :(得分:2)

您可以尝试对productData使用监视程序,该监视程序会在productData更改时设置您的名称。当我遇到类似的问题时,这对我有用。
因此,请添加您的导出默认设置

'=SUM(Blad1!A:A)

答案 1 :(得分:1)

您可以将钩子mounted更改为created

created() {
            this.setProductData();
        }

您还可以使用Computed Properties and Watchers

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