vue自动配置组件
-
使用
components的传统方法<script> import helloWorld from '@/components/helloWorld' import myPoint from '@/components/my/point' components: { helloWorld, myPoint } </script> <html> <hello-world /> <my-point /> </html> -
配置自动引入组件,无需
js引入,挂载,直接使用-
新建
js文件,ex:index.js -
js代码import Vue from 'vue' // components文件夹下组件 let components = require.context('@/components',true,/\.vue$/) // pages下components文件夹下组件 let pageCompoonents = require.context('@/pages',true,/\.vue$/) let autoComponents = (components,type) => { components.keys().forEach(key => { let componentsEntity = components(key).default let name = componentsEntity.name || key.replace('./','').replace('.vue','').replace('components/','').replace(/\//i,'-') if(type == 'page' && key.indexOf('components') == -1) { return false } Vue.component(name,componentsEntity) }) } autoComponents(components) autoComponents(pageCompoonents,'page') -
main.js中引入 -
页面中使用<html> <helloWorld /> // 注意,不能写成hello-world(这表示/hello/world,而不是我们需要的/helloWorld) <my-point /> // /my/point </html>
-