只需5步,教你实现Vue组件封装
2020-06-08 04:31
411 查看
虽然Vue有着诸如Element、Vant、iView等优秀的UI组件库,但是在日常开发中难免会有这些组件库难以满足的组件开发需求。这时就需要我们自己来封装组件。下面就来教大家如何封装一个button组件。
- 在components文件夹内创建一个hee-button文件夹,再在hee-button文件夹中创建一个src文件夹,src文件夹中创建一个main.vue文件。
<template> <div> <button :class="type==='primary'?'primary btn':type==='danger'?'danger btn':type==='warn'?'warn btn':'default btn'"> <slot>按钮</slot> </button> </div> </template> <script> export default { name: 'hee-button', props: { type: { type: String, default: 'default' } } } </script> <style scoped> .btn{ width: 80px; height: 30px; } .default{ background: #f00; } .primary{ background: #0f0; } .danger{ background: #00f; } .warn{ background: #ff0; } </style>
- 与src文件夹平级再创建一个index.js文件。
import Button from './hee-button.vue' Button.install = (Vue) => { Vue.component(Button.name, Button) } export default Button
- 与hee-button文件同级建立一个index.js文件,对组件进行注册,同时也注册进install中,在导出时,不仅要引出全局的,而且单个的也要引出,便于局部或全局引用。
import Button from './hee-button' const components = [ Button ] // vue.use使用时,必须要有install方法。参数就是vue。 const install = (Vue) => { for (var key in components) { Vue.component(components[key].name, components[key]) } } export default { install, Button }
- 在main.js中进行引用
import Vue from 'vue' import App from './App.vue' import router from './router' import HeeButton from './components' Vue.use(HeeButton) Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
- 组件封装完成,在App.vue中可以进行使用了。
<template> <div id="app"> <hee-button></hee-button> <hee-button type="primary">primary</hee-button> <hee-button type="danger">danger</hee-button> <hee-button type="warn">warn</hee-button> </div> </template>
效果如下:
相关文章推荐
- vue elementui 实现搜索栏公共组件封装的实例代码
- vue 封装组件 实现自定义双向绑定
- vue实现图片预览组件的封装与使用
- vue-cli3项目使用mint-ui 利用popup结合picker实现省市联动封装组件......
- vue实现图片预览组件封装与使用
- Vue封装 swiper 组件多种方案实现
- Vue中的transition封装组件的实现方法
- 二次封装el-button实现的vue权限按钮组件
- Vue + Element-ui实现后台管理系统(4)---封装一个ECharts组件的一点思路
- Vue + Element UI 实现权限管理系统 前端篇(七):功能组件封装
- Vue2.0+ElementUi封装table组件实现分页功能
- 实现axios的统一封装API,axios结果格式处理,vue组件的loading动画变量在axios请求的前后改变
- Vue组件的两种封装方式——分别实现自定义Toast的封装
- 从组件封装看Vue的作用域插槽的实现
- echarts图表刷新:vue中传递数据给子组件,并且监听子组件中数据的变化,实现刷新echarts图表的功能
- 基于elementUI使用v-model实现经纬度输入的vue组件
- iOS组件封装的思路和实现
- vue项目在同一页面中引入多个echarts图表 ,并实现封装,自适应和动态数据改变
- Vue.js组件实现选项卡以及切换特效
- Vue父子组件双向绑定传值的实现方法