vue簡單插件
阿新 • • 發佈:2019-03-20
調用 tco aci 需要 con ons 一個 template port
已經很久沒有學習新的相關知識,對於今後的學習方向可能會集中在vue的源碼,render,jsx語法,服務端渲染來學習,鞏固好vue的基礎和高級的知識,現階段vue的api和基本用法已經全部掌握,但是還是要深入學習,不能只知道api而已!
最近的項目中使用了vant的toast提示框,後來ui出圖需要使用自己定義的樣式,故看了下插件的寫法,寫了一次toast插件,鑒於需求比較少可能比較簡單
首先需要寫好頁面的模板,布局
<template> <transition name="fadeIn"> <div class="contain"v-if="show"> <div class="wrap" :class="{active:type == ‘success‘ || type == ‘fail‘}"> <img src="../../assets/images/successToast.png" v-if="type == ‘success‘"> <img src="../../assets/images/failToast.png" v-else-if="type == ‘fail‘"> <div class="text">{{message}}</div> </div> </div> </transition> </template> <script> export default { data(){ return { type:‘‘, message:‘‘, show:false, } } } </script> <style lang="scss" scoped> .contain{ width: 100%; position: fixed; left: 50%; top: 50%; transform: translate(-50%,-50%); text-align: center; z-index: 9999; } .wrap{ display: inline-block; max-width: 600px; background: rgba(0,0,0,.8); padding: 50px; border-radius: 10px; box-sizing: border-box; color:#fff; text-align: center; &.active{ width: 380px; } img{ width: 86px; } .text{ text-align: center; font-size: 28px; word-break: break-all; } } .fadeIn-enter-active, .fadeIn-leave-active{ transition: opacity .3s; } .fadeIn-enter, .fadeIn-leave-active{ opacity: 0; } </style>
緊接著需要使用vue的install來註冊插件,全局插入提示組件,控制顯示
import toastComponent from ‘./toast.vue‘ const Toast = {}; Toast.install = function (Vue) { // 生成一個Vue的子類 const ToastConstructor = Vue.extend(toastComponent) // 生成一個該子類的實例 const instance = new ToastConstructor(); // 將這個實例掛載在我創建的div上 // 並將此div加入全局掛載點內部 instance.$mount(document.createElement(‘div‘)) document.body.appendChild(instance.$el) // 通過Vue的原型註冊一個方法 // 讓所有實例共享這個方法 // 其中的duration是持續時間 Vue.prototype.$toast = (data,duration = 2000) => { if(Object.prototype.toString.call(data) == "[object Object]"){ instance.message = data.message; instance.type = data.type; instance.show = true; } else if(typeof(data) == ‘string‘){ instance.message = data; instance.show = true; } setTimeout(() => { instance.show = false; }, data.duration ? data.duration :duration); } } export default Toast
現在基本的功能已經實現,在main.js裏面進行註冊接全局調用$toast方法來使用tost組件
import toastRegistry from ‘./common/toast/index‘
Vue.use(toastRegistry)
實現的頁面效果分別如下:
vue簡單插件