Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Vue JS中使用v-for为组件设置道具_Javascript_Vuejs2_Vue Component - Fatal编程技术网

Javascript 在Vue JS中使用v-for为组件设置道具

Javascript 在Vue JS中使用v-for为组件设置道具,javascript,vuejs2,vue-component,Javascript,Vuejs2,Vue Component,我有一个PhoneCard.vue组件,我正试图将道具传递给它 <template> <div class='phone-number-card'> <div class='number-card-header'> <h4 class="number-card-header-text">{{ cardData.phone_number }}</h4> <spa

我有一个PhoneCard.vue组件,我正试图将道具传递给它

<template>
    <div class='phone-number-card'>
        <div class='number-card-header'>
            <h4 class="number-card-header-text">{{ cardData.phone_number }}</h4>
            <span class="number-card-subheader">
                {{ cardData.username }}
            </span>
        </div>
    </div>
</template>

<script>
export default {
    props: ['userData'],
    components: {
    },
    data() {
        return {
            cardData: {}
        }
    },
    methods: {
        setCardData() {
            this.cardData = this.userData;
            console.log(this.cardData);
        }
    },
    watch: {
        userData() {
            this.setCardData();
        }
    }
}
然后,一旦我将来自ajax调用的响应数据设置为phoneNumbers属性

问题出现后,我尝试遍历phoneNumber数组中的每个数字,并将当前正在遍历的数字的值绑定到卡的组件,如下所示:

<phone-card v-for="number in phoneNumbers" :user-data="number"></phone-card>

但是,这会导致开发工具中出现错误,例如属性用户名未定义、错误呈现组件、无法读取未定义的属性拆分

我尝试过其他方法,但它们似乎都会导致相同的错误。关于如何将组件的道具正确绑定到vue for循环的当前迭代对象,有什么想法吗?

试试看

export default {
    props: ['userData'],
    data() {
        return {
            cardData: this.userData
        }
    }
}

经过一番修补,我回答了自己的问题

我所要做的不是调用函数来设置watch函数中的数据,而是让它工作

mounted() {
    this.cardData = this.userData;
}

奇怪的是,我以前使用过watch方法来监听组件道具的变化,它工作得非常完美,但我猜这里发生了一些不同的事情。任何关于什么是不同的或者为什么它是这样工作的见解都是很酷的

妈的,在看到你的答案之前我已经失去了一天。伯恩,你对这种行为有什么解释吗?
mounted() {
    this.cardData = this.userData;
}