vue組件
countdown.vue
index.js
import countdown from './countdown.vue'
export {countdown}
從.vue文件直接引入組件,導出即可,組件就是一堆vue對象的options
vue插件
插件的方便之處,就是可以在install方法種執行任何動作,包括直接用 Vue.component 方法注冊該組件為全局組件,use一次之后,無需在文件中引入,十分方便
一個toast組件是實現思路:
1. 從.vue文件直接引入組件對象
2. 用Vue.extend初始化該組件對象為一個Vue子構造函數
3. 合並和處理方法接收的選項參數
4. 在cache對象中,查找該toast,有就復用,沒有就用前面的子構造函數新建
5. 通過$el屬性判斷是否已經渲染,沒有渲染,就通過$mount方法在內存中渲染,使用appendChild添加到body中
6. 把進來的選項都加入到隊列,方便處理多個實例的效果
7. 在Vue實例和Vue的prototype上分別添加全局和實例toast方法,如此可以全局或在組件中用this調用toast,彈出toast
8. 在全局和實例上,注冊clearToast方法,方便在某些場合,移除單個或全部的toast,例如:在router-after的全局鈎子中,
一旦頁面切換,前一個頁面的所有taost應該立即關閉,后續異步函數中的toast,也不應該再彈出。
import toast from './toast.vue' export default { install(Vue, defaultOptions = {}) { const CONSTRUCTOR = Vue.extend(toast) const CACHE = {} Object.assign(toast.DEFAULT_OPT, defaultOptions) function toast() { const args = arguments, toString = Object.prototype.toString; options.msg = msg; let toast = CACHE[options.id] || (CACHE[options.id] = new CONSTRUCTOR) if (!toast.$el) { let vm = toast.$mount() document.querySelector(options.parent || 'body').appendChild(vm.$el) } options = assign({},toast.DEFAULT_OPT,options); //使用隊列控制,toast多個實例彈出的效果,是覆蓋,還是堆疊 toast.queue.push(options) } Vue.toast = Vue.prototype.$toast = toast; Vue.clearToast = Vue.prototype.$clearToast = function(id){ if(id) removeChild(id); else{ Object.keys(CACHE).forEach(item => { removeChild(item); }); } } } }