vue做移動端經常碰到彈窗的需求, 這里寫一個功能簡單的vue彈窗
popup.vue
<template> <div class="popup-wrapper" v-show="visible" @click="hide"> <div class="popup-text">{{text}}</div> </div></template>
組件html結構, 外層divposition:fixed定位, 內層div顯示彈窗內容
export default { name: 'popup', props: { text: { //文字內容 type: String, default: '' }, time: { //顯示的時長 type: Number, default: 3e3 }, }, data(){ return { visible: false } }, methods: { open() { this.visible = true clearTimeout(this.timeout); this.$emit('show') if(this.time > 0){ this.timeout = setTimeout(() => { this.hide() }, this.time) } }, hide() { this.visible = false this.$emit('hide') clearTimeout(this.timeout); } }}
popup.vue只有2個屬性: 文本和顯示時間。組件顯示隱藏由內部屬性visible控制,只暴露給外界open和hide2個方法,2個方法觸發對應的事件
測試一下
<template> <popup ref="popup" text="彈窗內容" :time="1e3"></popup></template><script>import Popup from '@/components/popup' ... this.$refs.popup.open() ...</script>
插件化
組件功能寫好了,但是這種調用方式顯得很累贅。舉個例子layer.js的調用就是layer.open(...)沒有import,沒有ref,當然要先全局引用layer。我們寫的彈窗能不能這么方便呢,為此需要把popup改寫成vue插件。
說是插件,但能配置屬性調用方法的還是組件本身,具體是實例化的組件,而且這個實例必須是全局單例,這樣不同vue文件喚起popup的時候才不會打架
生成單例
// plugins/popupVm.jsimport Popup from '@/components/popup'let $vmexport const factory = (Vue)=> { if (!$vm) { let Popup = Vue.extend(PopupComponent) $vm = new Popup({ el: document.createElement('div') }) document.body.appendChild($vm.$el) } return $vm}
組件實例化后是添加在body上的,props不能寫在html里需要js去控制,這里寫個方法讓屬性默認值繼續發揮作用
// plugins/util.jsexport const setProps = ($vm, options) => { const defaults = {} Object.keys($vm.$options.props).forEach(k => { defaults[k] = $vm.$options.props[k].default }) const _options = _.assign({}, defaults, options) for (let i in _options) { $vm.$props[i] = _options[i] }}
// plugins/popupPlugin.jsimport { factory } from './popupVm'import { setProps } from './util'export default { install(Vue) { let $vm = factory(Vue); const popup = { open(options) { setProps($vm, options) //監聽事件 typeof options.onShow === 'function' && $vm.$once('show', options.onShow); typeof options.onHide === 'function' && $vm.$once('hide', options.onHide); $vm.open(); }, hide() { $vm.hide() }, //只配置文字 text(text) { this.open({ text }) } } Vue.prototype.$popup = popup }}
在main.js內注冊插件
//main.jsimport Vue from 'vue'import PopupPlugin from '@/plugins/popupPlugin'Vue.use(PopupPlugin)在vue框架內調用就非常方便了<script> ... this.$popup.text('彈窗消息') ...</script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答