我有一个可重复使用的组件,我想在任何我想要的组件中使用它:
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)..
那么我怎样才能做到这一点?
答案 0 :(得分:0)
您遇到了ShardIterator AFTER_SEQUENCE_NUMBER的问题,其中您无法实现使用子组件方法的尝试,因为它的用法属于父级编译范围而不属于子级。
要解决此问题并启用父子之间的通信,您应该发送带有Compilation Scope所述事件的消息。
下面是一个可能的解决方案:
<强> 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>