需求
一些常用的组件,如提示框、模态框等,为了防止频繁使用 import
引入费时费力,我们可以将其修改为使用 this
+ 方法名调用。
解决方案
根据需求,首先想到的就是将组件挂载到 Vue.prototype
上,所以我们可以开发 Vue
插件来完成。
插件通常用来为
Vue
添加全局功能
官方文档
接下来我们创建一个简易的提示框组件。
步骤:
在 src
目录下创建一个 pop
文件夹,在该文件下创建两个文件 Pop.vue
和 index.js
// Pop.vue
<template>
<div
class="tips animation"
v-show="isShow"
:class="{ shake: type === 'shake' }"
ref="tips"
>
<div class="content">{{ msg }}</div>
</div>
</template>
<script>
export default {
name: 'Pop',
props: {
// 类型
type: {
type: String,
default: ''
},
// 提示信息
msg: {
type: String,
default: ''
},
// 显示隐藏
isShow: {
type: Boolean,
default: false
}
},
watch: {
isShow (newval, oldval) {
if (newval !== oldval && newval === true) {
setTimeout(() => {
const height = this.$refs.tips.clientHeight
const width = this.$refs.tips.clientWidth
this.$refs.tips.style.marginLeft = -width / 2 + 'px'
this.$refs.tips.style.marginTop = -height / 2 + 'px'
}, 0)
setTimeout(() => {
this.isShow = false
this.msg = ''
this.type = ''
}, 3000)
}
}
}
}
</script>
<style lang="scss" scoped>
@keyframes shake {
0%,
100% {
transform: translateX(0);
}
10%,
30%,
50%,
70%,
90% {
transform: translateX(-10%);
}
20%,
40%,
60%,
80% {
transform: translateX(10%);
}
}
.tips {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 99;
}
.animation {
animation-fill-mode: both;
animation-duration: 0.3s;
}
.content {
background: rgba($color: #000000, $alpha: 0.4);
color: #fff;
border-radius: 6px;
padding: 10px 15px;
}
.shake {
animation-name: shake;
}
</style>
下面是重点内容,开发插件。
Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:
// index.js
import PopComponent from './Pop.vue'
const Pop = {}
Pop.install = Vue => {
const PopConstructor = Vue.extend(PopComponent)
const instance = new PopConstructor()
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
Vue.prototype.$pop = (type, msg) => {
instance.type = type
instance.msg = msg
instance.isShow = true
}
}
export default Pop
最后在 main.js
中加入
// 引入js
import Pop from './components/pop'
Vue.use(Pop)
完成以上步骤,就可以在任意页面使用 this.$pop('shake', '请先登录')
使用该组件了。