我有一个可重用的组件,我想在任何我想要的组件中使用它:
reusable.vue
<template>
<div class="example">
<slot></slot>
</div>
</template>
<script>
export default {
methods: {
alertme() {
console.log("hey!");
}
}
};
</script>
在另一个组件中,我想使用该组件(reusable.vue)的方法和数据。等
<template>
<reusable>
<template slot-scope="defaultSlotScope">
<button type="button" class="btn btn-danger" @click="alertme">click me!</button>
</template>
</reusable>
</template>
<script>
import reusable from "../reusable.vue";
export default {
components: {
reusable
}
};
</script>
我收到这个错误:
[Vue warn]: Property or method "alertme" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
这意味着Vue无法识别此方法(Alertme)。
那么,我如何才能让它工作呢?
发布于 2018-06-06 05:47:58
您正面临着一个Compilation Scope问题,您尝试使用子组件的方法无法实现,因为它的使用属于父组件的编译范围,而不是子组件的编译范围。
为了解决这个问题并实现父子节点之间的通信,您应该按照here的描述发送带有事件的消息。
下面是一个可能的解决方案:
reusable.vue
<template>
<div class="example" v-on:my-event="alertme">
<slot></slot>
</div>
</template>
<script>
export default {
methods: {
alertme() {
console.log("hey!");
}
}
};
</script>
使用reusable.vue的组件
<template>
<reusable>
<template slot-scope="defaultSlotScope">
<button type="button" class="btn btn-danger" @click="$emit('my-event')">click me!</button>
</template>
</reusable>
</template>
<script>
import reusable from "../reusable.vue";
export default {
components: {
reusable
}
};
</script>
https://stackoverflow.com/questions/50704847
复制相似问题