首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何访问子组件在其他组件中的方法?

如何访问子组件在其他组件中的方法?
EN

Stack Overflow用户
提问于 2018-06-06 00:26:07
回答 1查看 647关注 0票数 0

我有一个可重用的组件,我想在任何我想要的组件中使用它:

reusable.vue

代码语言:javascript
复制
<template>
    <div class="example">
        <slot></slot>
    </div>
</template>
<script>
export default {
  methods: {
    alertme() {
      console.log("hey!");
    }
  }
};
</script>

在另一个组件中,我想使用该组件(reusable.vue)的方法和数据。等

代码语言:javascript
复制
<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>

我收到这个错误:

代码语言:javascript
复制
[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)。

那么,我如何才能让它工作呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 05:47:58

您正面临着一个Compilation Scope问题,您尝试使用子组件的方法无法实现,因为它的使用属于父组件的编译范围,而不是子组件的编译范围。

为了解决这个问题并实现父子节点之间的通信,您应该按照here的描述发送带有事件的消息。

下面是一个可能的解决方案:

reusable.vue

代码语言:javascript
复制
<template>
<div class="example" v-on:my-event="alertme">
    <slot></slot>
</div>
</template>
<script>
export default {
  methods: {
    alertme() {
      console.log("hey!");
    }
  }
};
</script>

使用reusable.vue的组件

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50704847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档