javascript - 动态注册本地 Vue.js 组件

标签 javascript vue.js

我们知道 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 可以完美地满足这一点。

另请参阅 Automatic Global Registration of Base Components 的文档.

关于javascript - 动态注册本地 Vue.js 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622425/

相关文章:

javascript - nuxt 应用程序部署到 Netlify : fetch to api working locally, 但不在部署的站点上:收到 404

javascript - 让 Vue 解释以编程方式插入的组件

javascript - 根据选项将 axios.get URL 传递到 axios.all

javascript - 重构以删除尾随 <br>

javascript - jquery $(this).attr(…) 返回未定义

php - 在 JavaScript 中嵌入 PHP

javascript - 将动态内容加载到页面

javascript - 在 JS 循环中动态创建 JSON 键

javascript - Vuex,命名空间模块 setter/getter 在根 setter/getter 中不可用?

javascript - 使用django-cms配合VueJS打破了前端编辑