首先在components文件夹下创建一个你要封装的组件文件夹
比如components → demo → x-button.vue 路径下封装一个button的点击事件
<template>
<div>
<el-button type="primary" @click="handleSubmit">主要按钮</el-button>
</div>
</template>
<script>
export default {
name:'x-button' ,
methods: {
handleSubmit(){
console.log("按钮点击了");
}
},
}
</script>
<style lang='less' scoped>
</style>
组件已经写好了 , 然后就是全局引用它 , 或者局部引用它了
全局引用组件
在main.js文件里面引入它
import xButton from '@/components/demo/x-button'
Vue.component('x-button', xButton);
需要调用组件的页面
直接这样使用组件就可以了
<template>
<div>
<x-button></x-button>
</div>
</template>
如果是局部引入的话
在引入的页面
<template>
<div>
<x-button></x-button>
</div>
</template>
<script>
// 引入封装的组件
import xButton from "@/components/demo/x-button";
export default {
name: "demo",
// 调用的组件
components: {
xButton,
}}
</script>
这样就封装完了一个最简单的组件