在vue-cli里面 如何自己封装一个组件

首先在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>

这样就封装完了一个最简单的组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值