我们知道 possible像这样动态注册全局 Vue.js(版本 1)组件:
Vue.component('my-component', MyComponent)
有没有办法对本地组件执行相同的操作,即那些仅对特定组件可用/可见的组件?
我的想法是,我希望能够像这样传递要在本地注册的组件:
<outer-component
:local-component-to-be-registered-dymanically="Foo"
>
所以在 outer-component
中我可以做:
created() {
this.someMethodINeedToRegisterLocalComponent('cool-component', this.localComponentToBeRegisteredDynamically);
},
最佳答案
这就是我最终导入和注册组件动态到本地组件的方式:
created() {
const requireComponent = require.context(
// The relative path of the components folder
"PATH/TO/COMPONENTS_FOLDER",
// Whether or not to look in subfolders
false,
// The regular expression used to match base component filenames
/[A-Z]\w+\.(vue|js)$/
);
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName);
console.log(componentConfig.default);
// Gets the file name regardless of folder depth
const componentName = fileName
.split("/")
.pop()
.split(".")[0];
// register the component locally
this.$options.components[componentName] = componentConfig.default;
});
}
请注意,组件必须在挂载之前注册,created
生命周期 Hook 可以完美地满足这一点。
关于javascript - 动态注册本地 Vue.js 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622425/