0

I have a navigation as a component in vue:

<template>
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse">
        <span class="navbar-toggler-icon"></span>
    </button>
        <a class="navbar-brand" href="">Website Builder</a>
        <div class="collapse navbar-collapse" id="navbarCollapse">
            <ul class="navbar-nav nav-fill w-100">
                <li class="nav-item">
                    <a class="nav-link" href="/#/create">Create</a>
                </li>
                <li class="nav-item">
                    <a v-on:click="hello" class="nav-link" href="/#/how">How</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/#/about">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/#/youtube">Videos</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/#/login">Go to main site</a>
                </li>
            </ul>
    </div>
</nav>
</template>

<script>

export default {
    data() {
        return {

        }
    },
    methods: //if I have hello function here it works
}

</script>

And my vue setup looks like this:

import Navigation from '../components/homeNavigation.vue';


Vue.component('navigation', Navigation);



new Vue({
    el: '#nav',
    methods:
        hello: function () {
            console.log('hi');
        } // I want it here so that it is available for all components within '#nav'
});

So basically I want to define it in new Vue so that is available across all components i.e if I would have another component inside #nav that function would work too. Can that be achieved or does it have to be within component itself?

1

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

7 Comments

This question would benefit from more context but this is the best direction.
Would this approach still be appropriate if I have 2 vue app on the page? i.e. nav and content. I only need this function available on nav as it going to switch between different components (different navs) depending on where user clicks
Yes, it simply merges the Mixin object into any Vue instance or component. If you want to pass the method down to the descendants you may also use provide / inject, although this functionality is really intended for component publishers, but here's how you would do that: jsfiddle.net/u33bwejj
Thanks for that, it really explains a lot. How about props?
The difference between provide/inject and passing a function through props is that a function passed through props always gets executed in the parent context: jsfiddle.net/043gzhtq. Wheras an injected function gets executed in the context of the component it was injected into: jsfiddle.net/euLmtv1v. Passing a function through props though, isn't the standard approach for code reuse. If you're considering these options then it's probably worth looking at this Github issue which explains why provide/inject was born.
|
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/[email protected]/dist/vue.js"></script>
<div class="app"></div>

3 Comments

Please could you provide me/us with example so others can find it easily
@Bsalex Why would OP resort to creating a plugin when there is no absolute need for it?
@samayo, I can not read the OP's mind. Is it clear to you why the OP needs hello method? It is not clear to me. But vue framework is so flexible that it is absolutely possible to do such a thing with it and here I'm showing how to do it.
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.

3 Comments

So in this case navigation is a child? <div id="nav"> <navigation></navigation> </div>
well you're registering 'navigation' as a component, so it will be the child of a root Vue, or another component. But it can have children of its own, and that's what I though you were asking about.
I am planning to have div and inside it all nav components <navigation></navigation><navigation2></navigation2> and here is only going to be ever one, function will be switching between them by using data parameter to toggle between them, if that makes sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.