[Vuejs]-Vue.js Property or method "hello" is not defined on the instance but referenced during render

4👍

If you want to reuse methods across components you should use a mixin which will merge the mixin methods into the given component:

const HelloMixin = {
  methods: {
    hello() {
      console.log('hi');
    }
  }
}

new Vue({
  el: '#app',
  mixins: [HelloMixin],
  created() {
    this.hello();
  },
})

Here’s the JSFiddle: https://jsfiddle.net/taxq569t/

1👍

Yes, you can do it with a plugin.
https://v2.vuejs.org/v2/guide/plugins.html

Vue.component('someComponent', {
  template: `
        <span>
            Example text <br/>
            {{globalMethod()}}
        </span>
  `
});


const MyPlugin = {
  install(Vue) {
    Vue.prototype.globalMethod = function () {
      return 'Global method result';
    }
  }
};

Vue.use(MyPlugin);

var instance = new Vue({
  el: '.app',
  template: '<someComponent />'
});
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<div class="app"></div>
👤Bsalex

0👍

If you want to call a method on ‘navigation’ from a child component, you can do it with this.$parent.hello(), but Vue components don’t (shouldn’t) call methods on their parents. Components declare their properties, and parents can provide them or not. Components can emit events, which parents can catch, or not. You should avoid directly calling methods.

Leave a comment