Vue作為最近最炙手可熱的前端框架,其簡(jiǎn)單的入門方式和功能強(qiáng)大的API是其優(yōu)點(diǎn)。而同時(shí)因?yàn)槠銩PI的多樣性和豐富性,所以他的很多開發(fā)方式就和一切基于組件的React不同,如果沒有對(duì)Vue的API(有一些甚至文檔都沒提到)有一個(gè)全面的了解,那么在開發(fā)和設(shè)計(jì)一個(gè)組件的時(shí)候有可能就會(huì)繞一個(gè)大圈子,所以我非常推薦各位在學(xué)習(xí)Vue的時(shí)候先要對(duì)Vue核心的所有API都有一個(gè)了解。
舉個(gè)例子,通知組件notification基本是現(xiàn)代web開發(fā)標(biāo)配,在很多地方都能用到。而在以Vue作為核心框架的前端項(xiàng)目中,因?yàn)閂ue本身是一個(gè)組件化和虛擬Dom的框架,要實(shí)現(xiàn)一個(gè)通知組件的展示當(dāng)然是非常簡(jiǎn)單的。但因?yàn)橥ㄖM件的使用特性,直接在模板當(dāng)中書寫組件并通過v-show或者props控制通知組件的顯示顯然是非常不方便的,而且如果要在action或者其他非組件場(chǎng)景中要用到通知,那么純組件模式的用法也無(wú)法實(shí)現(xiàn)。那么有沒有辦法即用到Vue組件化特性方便得實(shí)現(xiàn)一個(gè)通知組件的展現(xiàn),又能夠通過一個(gè)簡(jiǎn)單的方法調(diào)用就能顯示通知呢?本文就是來(lái)講述這個(gè)實(shí)現(xiàn)方法的。
目標(biāo)
實(shí)現(xiàn)一個(gè)Vue的通知組件,可以直接在組件內(nèi)調(diào)用
通過方法調(diào)用,比如Vue.$notify({...options})來(lái)調(diào)用通知組件
結(jié)合上述兩種方式,復(fù)用代碼
實(shí)現(xiàn)通知組件
這一步非常的簡(jiǎn)單,我相信做過一點(diǎn)Vue開發(fā)的同學(xué)都能寫出一個(gè)像模像樣的通知組件,在這里就不贅述,直接上代碼
<template> <transition name="fade" @after-leave="afterLeave" @after-enter="setHeight"> <div v-show="visible" :class="['notification']" :style="style" @mouseenter="clearTimer" @mouseleave="createTimer" > <span class="content">{{content}}</span> <a class="btn" @click="handleClose">{{btn || '關(guān)閉'}}</a> </div> </transition></template><script>export default { name: 'Notification', props: { content: { type: String, default: '' }, btn: { type: String, default: '' } }, data () { return { visible: true } }, computed: { style () { return {} } }, methods: { handleClose (e) { e.preventDefault() this.doClose() }, doClose () { this.visible = false this.$emit('close') }, afterLeave () { this.$emit('closed') }, clearTimer () {}, createTimer () {}, setHeight () {} }}</script><style lang="stylus" scoped>.notification display: flex background-color #303030 color rgba(255, 255, 255, 1) align-items center padding 20px position fixed min-width 280px box-shadow 0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12) flex-wrap wrap transition all .3s.content padding 0.btn color #ff4081 padding-left 24px margin-left auto cursor pointer</style>
新聞熱點(diǎn)
疑難解答
圖片精選