【问题标题】:Call Methods of Mixin within Component (Vuejs)组件内 Mixin 的调用方法(Vuejs)
【发布时间】:2018-04-17 00:18:57
【问题描述】:

我无法从组件调用 mixin 方法,我收到此错误this.hello is not a function。

我可以从 Vue 实例调用hello(),但我不能在组件中调用它。

怎么了?!

<div id='vue-app'>
  <cmp></cmp>
</div>
const mixin = {
  methods: {
    hello() {
      return 'Hello World!';
    }
  },
  created() {
    console.log('Mixin Created!');
  },
};

const cmp = {
  created() {
    console.log('From Cmp:', this.hello());
  },
};

new Vue({
  components: {
    cmp
  },
  el: '#vue-app',
  mixins: [mixin],
  created() {
    console.log('From VM:', this.hello());
  },
});

https://jsfiddle.net/ar464soq/

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    正确,mixin 方法/数据仅在其添加到的实例中可用。但是,如果您真的想要根实例中的 mixin,您可以从根实例的任何子组件调用 this.$root.hello()

    【讨论】:

      【解决方案2】:

      好吧,看来我必须在整个 Component 实例中加载 Mixin,而不是从 Vue 父实例 :)

      【讨论】:

      • 有没有一种方法我们只需要在 vue 父组件上声明,所以我们需要在子组件中再次重新声明它?
      【解决方案3】:

      如果你在 vue 中使用 nuxt,@daxigu 将不起作用,因为 $root 是 nuxt 它自己。我能做些什么?这个:

      this.$root.$children[1].myRootMethod()
      
      • $root:正如我之前所说,这是 nuxt。

      • $children[0]: 正在加载。

      • $children[1]: 是你的主要组件,在我的例子中,它是一个包含一些全局组件和一个全局 mixin 的基本布局。

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2020-03-09
        • 1970-01-01
        • 2019-07-22
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 2021-03-14
        相关资源
        最近更新 更多