總結(jié) Vue 知識體系之高級技巧應(yīng)用篇

Vue.use
我們使用的第三方 Vue.js 插件。如果插件是一個對象,必須提供install方法。如果插件是一個函數(shù),它會被作為install方法。install方法調(diào)用時,會將Vue作為參數(shù)傳入。該方法需要在調(diào)用new Vue()之前被調(diào)用。
我們在使用插件或者第三方組件庫的時候用到Vue.use這個方法,比如
import iView from 'iview'
Vue.use(iView)那么Vue.use到底做了些什么事情呢?我們先來看一下源碼
import { toArray } from '../util/index'
export function initUse(Vue: GlobalAPI) {
Vue.use = function(plugin: Function | Object) {
const installedPlugins = this._installedPlugins || (this._installedPlugins = [])
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}我們由以上可以看出,plugin參數(shù)為函數(shù)或者對象類型,首先Vue會去尋找這個插件在已安裝的插件列表里有沒有,如果沒有,則進行安裝插件,如果有則跳出函數(shù),這保證插件只被安裝一次。
接著通過toArray方法將參數(shù)變成數(shù)組,再判斷plugin的install屬性是否為函數(shù),或者plugin本身就是函數(shù),最后執(zhí)行plugin.install或者plugin的方法。
下面我們來舉個實際例子?
1、編寫兩個插件
const Plugin1 = {
install(a) {
console.log(a)
}
}
function Plugin2(b) {
console.log(b)
}
export { Plugin1, Plugin2 }2、引入并 use 這兩個插件
import Vue from 'vue'
import { Plugin1, Plugin2 } from './plugins'
Vue.use(Plugin1, '參數(shù)1')
Vue.use(Plugin2, '參數(shù)2')此時我們運行項目代碼就可以用到上面兩個插件了。
Vue.mixin
混入 (mixin) 提供了一種非常靈活的方式,來分發(fā) Vue 組件中的可復用功能。一個混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被“混合”進入該組件本身的選項。
1、定義一個 mixin.js
export default mixin {
data() {
return {
name: 'mixin'
}
},
created() {
console.log('mixin...', this.name);
},
mounted() {},
methods: { //日期轉(zhuǎn)換
formatDate (dateTime, fmt = 'YYYY年MM月DD日 HH:mm:ss') {
if (!dateTime) {
return ''
}
moment.locale('zh-CN')
dateTime = moment(dateTime).format(fmt)
return dateTime
}
}
}2、在vue文件中使用mixin
import '@/mixin'; // 引入mixin文件
export default {
mixins: [mixin], //用法
data() {
return {
userName: "adimin",
time: this.formatDate(new Date()) //這個vue文件的數(shù)據(jù)源data里面的time就是引用混入進來的方法
}
}
}或者在全局中使用在main.js中,所有頁面都能使用了
import mixin from './mixin'
Vue.mixin(mixin)合并選項
當組件和混入對象含有同名選項時,這些選項將以恰當?shù)姆绞竭M行“合并”。
data對象在內(nèi)部會進行遞歸合并,并在發(fā)生沖突時以組件數(shù)據(jù)優(yōu)先。同名鉤子函數(shù)將合并為一個數(shù)組,因此都將被調(diào)用。混入對象的鉤子將在組件自身鉤子之前調(diào)用。
值為對象的選項,例如?
methods、components?和?directives,將被合并為同一個對象。兩個對象鍵名沖突時,取組件對象的鍵值對。
Vue.extend
Vue.extend?屬于 Vue 的全局 API。它使用基礎(chǔ) Vue 構(gòu)造器,創(chuàng)建一個“子類”。參數(shù)是一個包含組件選項的對象。如下:
"app">div>
var Profile = Vue.extend({
template: '{{firstName}} {{lastName}}
',
data: function () {
return {
firstName: 'Walter',
lastName: 'White'
}
}
})
// 創(chuàng)建 Profile 實例,并掛載到一個元素上。
new Profile().$mount('#app')我們常用?Vue.extend?封裝一些全局插件,比如?toast,?diolog?等。
下面以封裝一個?toast?組件為例。
1、編寫組件
根據(jù)傳入的 type 確定彈窗的類型(成功提示,失敗提示,警告,加載,純文字)
設(shè)置彈窗消失的時間
<template>
<div>
<transition name="fade">
<div class="little-tip" v-show="showTip">
<img src="/success.png" alt="" width="36" v-if="type=='success'" />
<img src="/fail.png" alt="" width="36" v-if="type=='fail'" />
<img src="/warning.png" alt="" width="36" v-if="type=='warning'" />
<img src="/loading.png" alt="" width="36" v-if="type=='loading'" class="loading" />
<span>{{msg}}span>
div>
transition>
div>
template>
<script>
export default {
data() {
return {
showTip: true,
msg: '',
type: ''
}
},
mounted() {
setTimeout(() => {
this.showTip = false
}, 1500)
}
}
script>
<style lang="less" scoped>
/* 樣式略 */
style>
2、利用?Vue.extend?構(gòu)造器把?toast?組件掛載到?vue?實例下
import Vue from 'vue'
import Main from './toast.vue'
let Toast = Vue.extend(Main)
let instance
const toast = function(options) {
options = options || {}
instance = new Toast({
data: options
})
instance.vm = instance.$mount()
document.body.appendChild(instance.vm.$el)
return instance.vm
}
export default toast
3、在?main.js?引入?toast?組價并掛載在?vue?原型上
import Vue from 'vue'
import toast from './components/toast'
Vue.prototype.$toast = toast
4、在項目中調(diào)用
this.$toast({ msg: '手機號碼不能為空' })
this.$toast({
msg: '成功提示',
type: 'success'
})
Vue.extend 和 Vue.component 的區(qū)別
component是需要先進行組件注冊后,然后在?template?中使用注冊的標簽名來實現(xiàn)組件的使用。Vue.extend?則是編程式的寫法。
控制component的顯示與否,需要在父組件中傳入一個狀態(tài)來控制或者在組件外部用?v-if/v-show?來實現(xiàn)控制,而?Vue.extend?的顯示與否是手動的去做組件的掛載和銷毀。
Vue.directive
注冊或獲取全局指令。指令定義函數(shù)提供了幾個鉤子函數(shù)(可選):
bind: 只調(diào)用一次,指令第一次綁定到元素時調(diào)用,可以定義一個在綁定時執(zhí)行一次的初始化動作。
inserted: 被綁定元素插入父節(jié)點時調(diào)用(父節(jié)點存在即可調(diào)用,不必存在于 document 中)。
update: 被綁定元素所在的模板更新時調(diào)用,而不論綁定值是否變化。通過比較更新前后的綁定值。
componentUpdated: 被綁定元素所在模板完成一次更新周期時調(diào)用。
unbind: 只調(diào)用一次, 指令與元素解綁時調(diào)用。
下面封裝一個復制粘貼文本的例子。
1、編寫指令?copy.js
const vCopy = {
bind (el, { value }) {
el.$value = value // 用一個全局屬性來存?zhèn)鬟M來的值
el.handler = () => {
if (!el.$value) {
alert('無復制內(nèi)容')
return
}
// 動態(tài)創(chuàng)建 textarea 標簽
const textarea = document.createElement('textarea')
// 將該 textarea 設(shè)為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區(qū)域
textarea.readOnly = 'readonly'
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
// 將要 copy 的值賦給 textarea 標簽的 value 屬性
textarea.value = el.$value
// 將 textarea 插入到 body 中
document.body.appendChild(textarea)
// 選中值并復制
textarea.select()
// textarea.setSelectionRange(0, textarea.value.length);
const result = document.execCommand('Copy')
if (result) {
alert('復制成功')
}
document.body.removeChild(textarea)
}
// 綁定點擊事件,就是所謂的一鍵 copy 啦
el.addEventListener('click', el.handler)
},
// 當傳進來的值更新的時候觸發(fā)
componentUpdated (el, { value }) {
el.$value = value
},
// 指令與元素解綁的時候,移除事件綁定
unbind (el) {
el.removeEventListener('click', el.handler)
}
}
export default vCopy
2、注冊指令
import copy from './copy'
// 自定義指令
const directives = {
copy
}
// 這種寫法可以批量注冊指令
export default {
install (Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key])
})
}
}
3、在?main.js?引入并?use
import Vue from 'vue'
import Directives from './JS/directives'
Vue.use(Directives)
這樣就可以在項目直接用?vCopy?指令了。
最后
最近,小編的臉被打歪了,這篇文章:我的 2020 年終總結(jié) - 成長不及預(yù)期的 3 年之癢,可以知道為什么???
