简体   繁体   English

如何使用自定义 Vue 实例注入 Vue 组件

[英]How to inject Vue component using custom Vue instance

I've seen some plugins that use custom Vue instance to invoke their own vue components.我见过一些使用自定义 Vue 实例来调用自己的 Vue 组件的插件。 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 实例

 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.我不知道这种方法叫什么,所以我无法搜索互联网。

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 .另一方面,您可以使用VuexVue.observable But this is more complex if you are beginner.但如果你是初学者,这会更复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM