1.新建plugins、msg文件夹以及相关文件
- src/plugins/index.js
- src/plugins/msg/msg.vue
2.在msg.vue中实现消息通知的基本功能
- 点击按钮后弹出一个消息框,几秒之后消失
.msg.vue
<template>
<div>
<div class="msg" :class="{'active': msgStatus}">
<div class="msg-wrapper">
{{ text }}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'vue-msg',
data () {
return {
text: '',
msgStatus: false
}
},
methods: {
msgPlugin (msg, time = 2000) {
this.text = msg
this.msgStatus = true
setTimeout(() => {
this.msgStatus = false
}, time)
}
}
}
</script>
<style scoped>
.msg {
position: absolute;;
left: 50%;
top: 50%;
transform: translate(-50%,50%);
width:0px;
min-height:0px;
text-align:center;
background-color:rgba(0,0,0,0.5);
border-radius:5px;
color: #fff;
transition:all 0.5s;
z-index:999;
opacity:0;
}
.active {
width:150px;
min-height:25px;
opacity:1;
z-index:999;
}
</style>
3.在plugins/index.js 导出插件
//比较简单的写法,后面进行优化
import msg from './msg/msg'
let plugin = {}
plugin.install = function (Vue) {
Vue.component(msg.name, msg)
}
export default plugin
4.在main.js中引入该插件
import plugin from './plugins'
Vue.use(plugin)
5.在xxx.vue文件中使用vue-msg插件
<template>
<div class="hello">
<h1>this is hello word</h1>
<input placeholder="请输入" v-model="name"/>
<button @click="submit">提交</button>
<vue-msg ref="msg"/>
</div>
</template>
export default {
name: 'HelloWorld',
data () {
return {
name: ''
}
},
methods: {
submit () {
if (!this.name) {
this.$refs.msg.msgPlugin('姓名不能为空')
}
}
}
}
至此已经完成一个插件的基本开发,但是实际工作中一定会需要在plugins/index.js中导入导出多个插件。第三步的写法不免有些繁琐。
下面提供一种更加优雅的写法
const requireComponent = require.context('./', true, /\.vue$/)
const install = (Vue) => {
if (install.installed) return
install.installed
requireComponent.keys().map(component => {
const config = requireComponent(component)
const componentName = config.default.name
Vue.component(componentName, config.default || config)
})
}
export default {
install,
// ...components
}
(完)
网友评论