从文件夹自动全局注册vue单文件组件
Automatic global register vue single file components from folder
我在 ./components/basic 文件夹中收集了所有简单的全局组件,我想在全局自动注册它。
代码如下:
import Vue from "vue";
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
const requireComponent = require.context('./components/basic/', true, /[A-Z]\w+\.(vue|js)$/);
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(camelCase(fileName.split('/').pop().replace(/\.\w+$/, '')));
Vue.component(componentName, componentConfig.default || componentConfig);
});
new Vue({
el: "#app"
});
index.html片段:
<body>
<div id="app">
<MyBasic></MyBasic>
</div>
<script src="./dist/main.js"></script>
</body>
最后一个组件MyBasic.vue:
<template>
<h1>My basic component</h1>
</template>
<script>
export default {
name: 'MyBasic',
data(){
return{
header: "Hi!"
}
}
}
</script>
<style></style>
一切似乎都是正确的,但实际上它向控制台发出警告并且我的组件不起作用:
[Vue warn]: Unknown custom element: <mybasic> - did you register the
component correctly? For recursive components, make sure to provide
the "name" option. (found in Root)
注册脚本出了什么问题?
问题是您直接在 DOM:
中使用 PascalCase
https://vuejs.org/v2/guide/components-registration.html#Name-Casing
Note, however, that only kebab-case names are valid directly in the DOM (i.e. non-string templates).
浏览器会将 <MyBasic>
转换为 <mybasic>
,如错误消息所示。您需要在 index.html
.
中使用 <my-basic>
另见 https://vuejs.org/v2/style-guide/#Component-name-casing-in-templates-strongly-recommended
我在 ./components/basic 文件夹中收集了所有简单的全局组件,我想在全局自动注册它。
代码如下:
import Vue from "vue";
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
const requireComponent = require.context('./components/basic/', true, /[A-Z]\w+\.(vue|js)$/);
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(camelCase(fileName.split('/').pop().replace(/\.\w+$/, '')));
Vue.component(componentName, componentConfig.default || componentConfig);
});
new Vue({
el: "#app"
});
index.html片段:
<body>
<div id="app">
<MyBasic></MyBasic>
</div>
<script src="./dist/main.js"></script>
</body>
最后一个组件MyBasic.vue:
<template>
<h1>My basic component</h1>
</template>
<script>
export default {
name: 'MyBasic',
data(){
return{
header: "Hi!"
}
}
}
</script>
<style></style>
一切似乎都是正确的,但实际上它向控制台发出警告并且我的组件不起作用:
[Vue warn]: Unknown custom element: <mybasic> - did you register the component correctly? For recursive components, make sure to provide the "name" option. (found in Root)
注册脚本出了什么问题?
问题是您直接在 DOM:
中使用 PascalCasehttps://vuejs.org/v2/guide/components-registration.html#Name-Casing
Note, however, that only kebab-case names are valid directly in the DOM (i.e. non-string templates).
浏览器会将 <MyBasic>
转换为 <mybasic>
,如错误消息所示。您需要在 index.html
.
<my-basic>
另见 https://vuejs.org/v2/style-guide/#Component-name-casing-in-templates-strongly-recommended