【发布时间】:2022-01-01 20:46:51
【问题描述】:
我正在努力重用我的组件。
我想将传递给我的组件的数据作为道具传递给另一个组件。
如果我这样做,vue 会抱怨道具的突变。
示例:
我想在我的应用的多个位置显示联系人。
为此,我创建了一个联系人组件来重用它:
<template>
<div>
<input :value="contact.firstName" @input="$emit('update:contact', {...contact, firstName: $event.target.value})">
<Mother v-model:mother="contact.mother"/>
</div>
</template>
<script>
import Mother from '@/components/Mother'
export default {
name: 'Contact',
components: {
Mother
},
props: {
contact: Object,
},
emit: ['update:contact'],
methods: {
}
}
</script>
每个联系人都有一个母亲,母亲不仅在联系人组件中显示在其他地方。 这就是为什么我创建了一个母组件,供联系人使用。
<template>
<div>
<input :value="mother.lastName" @input="$emit('update:mother', {...mother, lastName: $event.target.value})">
</div>
</template>
<script>
export default {
name: 'Mother',
props: {
mother: Object,
},
emit: ['update:mother'],
methods: {
}
}
</script>
现在我希望能够同时改变母亲的联系人,并且我希望能够在同一个站点上使用两个联系人组件。
如果我按照解释的方式使用它,我会收到此错误:
ERROR Failed to compile with 1 error 09:17:25
error in ./src/components/Contact.vue
Module Error (from ./node_modules/eslint-loader/index.js):
/tmp/vue-example/src/components/Contact.vue
4:27 error Unexpected mutation of "contact" prop vue/no-mutating-props
✖ 1 problem (1 error, 0 warnings)
我有一个示例项目显示我的问题: https://gitlab.com/FirstWithThisName/vue-example.git
感谢您的帮助
【问题讨论】:
-
您的项目正在运行。更详细地写下你不能做的事情
-
不,不是,如果您尝试使用 npm run serve 运行它,您会收到错误“接触”道具的意外突变'
-
正如它所说的,你不能改变一个道具。您应该查看使用 v-model 时自动传入的“modelValue”道具。并使用 watch/computed 属性而不是直接改变 prop 来跟踪更新的值。另外我没有看到链接 2 个输入组件的原因,为什么不将 2 个不同的组件拆分为“App.vue”呢?
-
@Cerceis 在另一个地方重用链接的组件。