一般常用的组件,比如输入框,按钮,modal,drawer等等需要经常用到,那么我们就可以将其封装成全组件;
而一般的项目中比如说一个需求,里面有很多重复的功能点需要拆分,这个可能只有当前项目会用到,所以没必要写成一个全局的,那么我们就需要局部注册
自定义组件(局部注册)
在自定义组件中写出你要写的功能或样式
在ExampleComponent.vue组件中:
<template>
<div>我是一个自定义组件</div>
</template>
<style>
// 这里写样式
</style>
<script lang="ts">
export default {
name: 'example-component',
data(){
return {}
}
}
</script>
在父组件中使用:
<template>
<ExampleComponent></ExampleComponent>
</template>
<script>
import ExampleComponent from "../component/ExampleComponent.vue";
export default {
name: "index",
data() {
return {};
},
components: {
ExampleComponent //ExampleComponent: ExampleComponent的简写
},
};
</script>
自定义组件(全局注册)
我的自定义全局组件目录结构如下:
index.js是一个入口文件,用来导出所有的公用组件,代码如下:
import dialog from './dialog';
const views = {
dialog,
}
const install = function (Vue) {
Object.keys(views).forEach((key) => {
Vue.component('po-'+key, views[key])
})
}
const API = {
install
}
export default API;
在main.js(也有可能是index.js)入口文件中引入components下的index.js:
import Components from './components/';
Vue.use(Components);
使用:
<po-dialog></po-dialog>
对你有用的话点个赞吧~