【发布时间】:2020-06-17 11:05:54
【问题描述】:
我正在尝试对组件库进行可视化表示。我正在使用动态<component>s 来渲染每个组件。但是,当我使用其插槽填充组件时,由于缺少父方法,我遇到了问题。
我希望组件可用(演示),因此我需要补偿this.$parent 不工作。
<template>
<component v-bind:is="'s-' + comp.name" v-bind="props" ref="comp"> <!-- this is the corrent parent-->
<div v-if="comp.slots">
<div
v-for="(slot, i) in comp.slots"
v-bind:key="i"
v-bind:slot="slot.name"
>
<div v-if="slot.type == 'component'"> <!-- childs parent -->
<de-mo v-bind:comp="slot" /> <!-- this is the child calling a method on the parent -->
</div>
<div v-html="slot.value" v-else></div>
</div>
</div>
</component>
</template>
<script>
export default {
name: 'deMo',
computed: {
props() {
if (this.comp.props) {
return this.comp.props.reduce((a, r) => {
a[r.name] = r.value
return a
}, {})
}
}
},
props: {
comp: {
type: Object,
required: true
}
},
methods: this.$ref.comp.methods, //<-- this is an error
mounted(){
console.log(this.$ref.comp.methods)
}
},
</script>
<style></style>
1) 有没有办法通过ref attr 将父级的方法复制到这个“演示”组件中
2) 或者,有没有更好的方法来产生相同的结果?
谢谢
【问题讨论】:
-
组件库应该使用 Inject 提供,这是推荐的方式,而不是直接的树父子关系,如果子元素在中间元素内则不起作用
标签: vue.js vuejs2 vue-component nuxt.js