动态注册本地 Vue.js 组件 [英] Register local Vue.js component dynamically

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

问题描述

我们知道可能注册全局 Vue.js(版本 1)像这样动态的组件:

We know it possible to register global Vue.js (version 1) components dynamically like this:

Vue.component('my-component', MyComponent)

有没有办法对本地组件执行相同的操作,即那些仅对特定组件可用/可见的组件?

Is there a way to do the same for local components, i.e. those available/visible only to a specific component?

这个想法是我希望能够像这样传递要在本地注册的组件:

The idea is that I want to be able to pass components to be locally registered like this:

<outer-component
  :local-component-to-be-registered-dymanically="Foo"
>

这样我就可以在 outer-component 中执行以下操作:

So that in the outer-component I could then do:

created() {
    this.someMethodINeedToRegisterLocalComponent('cool-component', this.localComponentToBeRegisteredDynamically);
},

推荐答案

这是您实现动态组件的方式,而不是注册动态组件的方式.在 .vue 文件中,您只能注册一个组件,其他任何组件都需要在外部定义.

This is how you implement a dynamic component, not how to register a dynamic component. In .vue files you can only register a single component, any others would need to be defined externally.

应该能够使用 :is 属性实现您希望完成的任务.以下是文档中的示例:

You should be able to achieve what you're looking to accomplish using the :is attribute. Here's the example from the docs:

var vm = new Vue({
    el: '#example',
    data: {
        currentView: 'home'
    },
    components: {
        home: { /* ... */ },
        posts: { /* ... */ },
        archive: { /* ... */ }
    }
})
<component v-bind:is="currentView">
    <!-- component changes when vm.currentView changes! -->
</component>

或者替代方法,直接绑定到组件对象(而不是使用一些数据作为指针):

or an alternative, where you bind directly to the component object (instead of using some data as a pointer):

var Home = {
    template: '<p>Welcome home!</p>'
}
var vm = new Vue({
    el: '#example',
    data: {
        currentView: Home
    }
})

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

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