0

I’ve seen some plugins that use custom Vue instance to invoke their own vue components. Something like

this.$activateLoadingBar.options({color:"Green", msg:"loading"})

Then a green loading bar pops up with “loading” as its message

I wanted to try and create myself. So I made a new component and declared a custom Vue instance by using

 Vue.prototype.$<name> = ...enter code here...

Then I am completely lost. What should I do so to get the result i needed ? I don’t know what is this method called, so i am unable search the internet.

1 Answer 1

2

You can use the Global Event Bus. See the example below:

<template>
  <div>
    <button @click="sendMessageToChild">Send message to child</button>
    <HelloWord />
  </div>
</template>

<script>
import HelloWord from '@/components/HelloWord.vue';

export default {
  name: 'App',
  components: { HelloWord },
  methods: {
    sendMessageToChild() {
      this.$root.$emit('messageToChild', 'any text');
    },
  },
};
</script>

<template>
  <div>x = {{ message }}</div>
</template>

<script>
export default {
  name: 'HelloWord',
  data() {
    return {
      message: '',
    };
  },
  mounted() {
    this.$root.$on('messageToChild', text => (this.message = text));
  },
};
</script>

In this example, there is two components (a parent and a child). The parent component call the child.

But you can change this, the child can call the parent.

Otherhand, you can use Vuex or Vue.observable. But this is more complex if you are beginner.

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

2 Comments

Thanks, i use Vuex , but i don't know how to call $root.$emit in Vuex.
If you use Vuex, you musn't call $root.$emit. With Vuex, you must create a state and a mutation. The Global Event Bus is indicated for simple cases.

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.