在vue項目中如果想封裝一個通用的vue組件,可以用slot+props的方式,也可以用extend的方式,看具體需求來確定用那種方式。
下面用extend封裝一個通用的提示框
首先先寫template模版 vAlert.vue
<template>
<div class="v-alert" v-if="show">
<b :class="type"></b>
<p :class="type" v-html="text"></p>
</div>
</template>
<script>
export default {
props: ['show', 'text', 'type']
}
</script>
<style lang="scss" scoped>
.v-alert{
width:100%;
height:pr(80);
padding:pr(20);
position: fixed;
top:pr(-80);
left:0;
z-index: 1999;
display: flex;
align-items: center;
background: #fff;
animation: show 3s;
b{
width:pr(36);
height:pr(36);
margin-right: pr(12);
&.warning{
background: url('~@/img/product/orderResult/failed.svg') no-repeat;
background-size: 100%;
}
&.success{
background: url('~@/img/product/orderResult/success.svg') no-repeat;
background-size: 100%;
}
}
p{
font-size: pr(28);
&.success{
color:#42b983;
}
&.warning{
color: #e96900;
}
}
@keyframes show {
0% {
top:pr(-80);
}
20% {
top:pr(0);
}
80% {
top:pr(0);
}
100% {
top:pr(-80);
}
}
}
</style>
然后是js文件 index.js
import Vue from 'vue' import vAlert from './vAlert.vue' // 獲取組件構造器 const VAlert = Vue.extend(vAlert) function AModal() { let VM = null return function(type, text) { if (!text) return if (!VM) { const oDiv = document.createElement('div') // 創建VAlert實例 VM = new VAlert({el: oDiv}) // 並把實例化的模板插入body document.body.appendChild(VM.$el) } // 設置屬性 VM.type = type VM.text = text VM.show = true setTimeout(() => { VM.show = false }, 3000) } } let SHOW = AModal() export default { warning: (v) => { SHOW('warning', v) }, success: (v) => { SHOW('success', v) } }
在引入使用時,可以直接掛載到prototype上,這樣就可以this直接調用了
import VAlert from "@/components/common/vAlert"
Vue.$VAlert = Vue.prototype.$VAlert = VAlert
使用
this.$VAlert.success('保存成功')
