Vuejs复制动态组件方法



我正在尝试对组件库进行可视化表示。我使用动态<component>来渲染每个组件。然而,当我用插槽填充组件时,由于缺少父方法,我遇到了问题。

我希望组件是可用的(演示(,因此我需要补偿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属性将方法从父级复制到这个"演示"组件中2( 或者,是否有更好的方法来产生相同的结果?

感谢

您可以尝试在beforeCreate生命周期中扩展父方法,因为此时您的父方法将被创建,并且您的组件将注册其所有方法

beforeCreate() {
this.$options.methods = { ...this.$parent.$options.methods };
},

但是,您不能访问其中的任何refs,因为refs仅在组件安装后注册。

注意:任何库都应该使用provide和inject与它们的组件通信,而不是直接引用父组件。

您可以使用事件总线在彼此不直接相关的组件之间进行通信。此外,这是推荐的Vue中从孩子到父母的沟通方式。

bus.js

import Vue from 'vue'
export default new Vue()

demo.vue//要调用父中方法的子组件

import Bus from './bus.js'
export default {
mounted () {
// [1] child component will emit an event in the bus when it want to call a method of parent 
Bus.$emit('invoke-parent-fn', 'param')
}
}

parent.vue//您想要动态呈现其他组件的父组件

import Bus from './bus.js'
export default {
methods: {
fn (param) {
console.log('// do something ' + param)
}
},
mounted () {
// [2] parent will be listening to the bus event, when child will emit an event, the handler passed in to the listener will be invoked
// [3] invoke the required method in the handler
Bus.$on('invoke-parent-fn', param => this.fn(param))
}
}

最新更新