将组件注册到现有的 Vue.js 实例 [英] Register a component to an existing Vue.js instance

查看:31
本文介绍了将组件注册到现有的 Vue.js 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Vue.js 的新手.

I'm new to Vue.js.

我想注册一个本地组件,如下所述:

I want to register a local component as described over here:

https://vuejs.org/v2/guide/components.html#本地注册

唯一的问题是我需要将组件注册到现有 Vue 实例,而不是在创建新实例时,例如:

The only issue is that I need to register a component to an existing Vue instance not while creating a new instance something like:

const app = new Vue({
    el: '#app'
});

app.component({
    'my-component': {
         template: '<div>A custom component!</div>'
    }
});

为此我尝试过 Vue.extend,但它不起作用.

I have tried Vue.extend for that, but it is not working.

为什么我需要这个:

我正在创建一个包含该组件的 3rd 方包.将安装此包的框架已经包含 Vue.js 和一个 Vue 实例.所以如果我在框架的 JS 之前包含我的包的 JS,那么它会给我 Vue 未定义,如果我在框架的 JS 之后包含我的包的 JS,那么它会给我组件错误,因为它必须在 Vue 实例化之前注册.

I'm creating a 3rd party package which will have that component. The framework on which this package is going to be installed will already have Vue.js included and a Vue instance. So if I include my package's JS before framework's JS, then it will give me Vue is undefined and if I include my package's JS after framework's JS, then it will give me component error as it has to be registered before the Vue instantiation.

推荐答案

全局组件应该在新实例构造之前声明.

Global components should be declared before new instance construct.

Vue.component('my-component-a', {
  template: '<div>A custom component A!</div>'
});

Vue.component('my-component-b', {
  template: '<div>A custom component B!</div>'
});

const app1 = new Vue({
    el: '#app1',
    template: '<div><my-component-a /><my-component-b /><my-component-c /></div>',
    components: {
      MyComponentC: {
        template: '<div>A custom component C!</div>'
      }
    }
});

const app2 = new Vue({
    el: '#app2',
    template: '<div><my-component-b /><my-component-a /><my-component-c /></div>'
});

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app1"></div>
<div id="app2"></div>

您无权从您的 app2 中访问 C 组件

You don't have access to the C component from within your app2

这篇关于将组件注册到现有的 Vue.js 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆