如何在 Vue.js 中的动态组件上使用组件特定属性?
How can I use component specific attributes on dynamic components in Vue.js?
我有两个使用组件元素显示的动态组件。
<keep-alive>
<component :is="activeOption" :resources="resources" @resourceAdded="addToList"></component>
</keep-alive>
其中一个组件需要道具 resources,而另一个组件发出自定义事件 resourceAdded。一切正常,除了我收到错误消息 'Extraneous non-emits event...' 和 'Extraneous non-emits props...' ,我理解这是因为它也在尝试传递 props 并从没有指定 props 或 emit 的组件发出自定义事件。我怎样才能解决这个问题而不必在两个组件中指定 emit 和 props?或者这就是这样做的方式?
第一个组件 - 只发射
<script>
export default {
emits: ['resourceAdded'],
// props: {
// resources: {
// type: Array,
// required: true
// }
// }, NO PROPS ERROR IF THIS IS SPECIFIED
data() {
return {
errorMsg: false
}
},
methods: {
addNewResource() {
const name = this.$refs.name.value
const description = this.$refs.description.value
const link = this.$refs.link.value
if(name === '' || description === '' || link === ''){
this.errorMsg = true
}else{
this.$emit("resourceAdded", name, description, link)
}
}
}
}
</script>
第二个组件 - 只需要道具
<script>
export default {
props: {
resources: {
type: Array,
required: true
}
},
// emits: ['resourceAdded'] NO EMITS ERROR IF THIS IS SPECIFIED
}
</script>
Vue.js 中有一个提供/注入功能,允许 parents 和 Vue.js 中的 children 之间的特定数据和函数通信。我发现它在这里很适合我,而且它也适合将一些 data/functions 传入或传出深度嵌套的 child,因此您不必将它传递给它的所有祖先。
我有两个使用组件元素显示的动态组件。
<keep-alive>
<component :is="activeOption" :resources="resources" @resourceAdded="addToList"></component>
</keep-alive>
其中一个组件需要道具 resources,而另一个组件发出自定义事件 resourceAdded。一切正常,除了我收到错误消息 'Extraneous non-emits event...' 和 'Extraneous non-emits props...' ,我理解这是因为它也在尝试传递 props 并从没有指定 props 或 emit 的组件发出自定义事件。我怎样才能解决这个问题而不必在两个组件中指定 emit 和 props?或者这就是这样做的方式?
第一个组件 - 只发射
<script>
export default {
emits: ['resourceAdded'],
// props: {
// resources: {
// type: Array,
// required: true
// }
// }, NO PROPS ERROR IF THIS IS SPECIFIED
data() {
return {
errorMsg: false
}
},
methods: {
addNewResource() {
const name = this.$refs.name.value
const description = this.$refs.description.value
const link = this.$refs.link.value
if(name === '' || description === '' || link === ''){
this.errorMsg = true
}else{
this.$emit("resourceAdded", name, description, link)
}
}
}
}
</script>
第二个组件 - 只需要道具
<script>
export default {
props: {
resources: {
type: Array,
required: true
}
},
// emits: ['resourceAdded'] NO EMITS ERROR IF THIS IS SPECIFIED
}
</script>
Vue.js 中有一个提供/注入功能,允许 parents 和 Vue.js 中的 children 之间的特定数据和函数通信。我发现它在这里很适合我,而且它也适合将一些 data/functions 传入或传出深度嵌套的 child,因此您不必将它传递给它的所有祖先。