当我们在项目中编写了组件后,我们会去界面中通过import的方式引入,然后在components中去注入,才能使用。如下:
import cForm from '@/components/self-components/form/form'
import cFormItem from '@/components/self-components/form/form-item'
import cInput from '@/components/self-components/form/input'
import cButton from '@/components/self-components/c-button'
import cCheckBox from '@/components/self-components/form/checkbox'
import cCheckBoxGroup from '@/components/self-components/form/checkbox-group'
export default {
name: "Demo02",
components:{
cForm,
cFormItem,
cInput,
cButton,
cCheckBox,
cCheckBoxGroup
},
}
这种我们会发现当组件很多的时候,我们要写很多的import,如果多个界面要用,我们可能会在多个界面写很多相同的import,或者直接在main.js中写一套import。这样会不会觉得繁琐呢?
下面介绍一种简便的方式
1、如图所示,我们创建一个文件plugins,在这个文件下编写我们所有的组件代码,其中index.js为入口文件。上面写了两个组件demo分别是button,msg.
2、我们在index.js入口文件中编写代码:
// 自动引入所有的vue文件
// ./为当前目录, true为是否匹配当前文件夹 /\.vue$/为匹配插件(匹配.vue结尾的插件)
const requireComponent = require.context('./', true, /\.vue$/);
const install = (Vue) => {
// 判断有没有被注册
// 如果注册过,就直接返回,否则就再注册一遍
if(install.installed){
return;
}else{
install.installed;
}
// 上述if else的简写
// if(install.installed) return
// install.installed
requireComponent.keys().forEach(fileName =>{
// 拿到第i个
const config = requireComponent(fileName) // 拿到的是vue文件的文件名
const componentName = config.default.name // 拿到的是vue文件中export default 下的name
Vue.component(componentName, config.default || config)
});
// 自定义指令 , 自动获取焦点去input上执行 v-focus
Vue.directive('focus',{
bind:function(){
},
// 当元素被插入界面的时候,就会被出发
inserted:function(el){
el.focus();
}
})
}
// 确保是正常环境
if(typeof window !== 'undefined' && window.Vue){
install(window.Vue);
}
export default {
install
}
3、在main.js文件中注册上述js文件
import plugins from './plugins/index.js'
Vue.use(plugins)
4、去界面中使用组件即可
<vue-button type="warn">警告按钮</vue-button>
<vue-msg ref="msg" ></vue-msg>
注意:
vue-button、vue-msg都是组件.vue文件中export default 下name中定义的名字。