Vue.use
我們使用的第三方 Vue.js 插件。如果插件是一個對象,必須提供install
方法。如果插件是一個函數,它會被作爲install
方法。install
方法調用時,會將Vue
作爲參數傳入。該方法需要在調用new Vue()
之前被調用。
我們在使用插件或者第三方組件庫的時候用到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
參數爲函數或者對象類型,首先Vue
會去尋找這個插件在已安裝的插件列表裏有沒有,如果沒有,則進行安裝插件,如果有則跳出函數,這保證插件只被安裝一次。
接着通過toArray
方法將參數變成數組,再判斷plugin
的install
屬性是否爲函數,或者plugin
本身就是函數,最後執行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, '參數1')
Vue.use(Plugin2, '參數2')
此時我們運行項目代碼就可以用到上面兩個插件了。
Vue.mixin
混入 (mixin) 提供了一種非常靈活的方式,來分發 Vue 組件中的可複用功能。一個混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被“混合”進入該組件本身的選項。
1、定義一個 mixin.js
export default mixin {
data() {
return {
name: 'mixin'
}
},
created() {
console.log('mixin...', this.name);
},
mounted() {},
methods: { //日期轉換
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文件的數據源data裏面的time就是引用混入進來的方法
}
}
}
或者在全局中使用在main.js中,所有頁面都能使用了
import mixin from './mixin'
Vue.mixin(mixin)
合併選項
當組件和混入對象含有同名選項時,這些選項將以恰當的方式進行“合併”。
data
對象在內部會進行遞歸合併,並在發生衝突時以組件數據優先。同名鉤子函數將合併爲一個數組,因此都將被調用。混入對象的鉤子將在組件自身鉤子之前調用。
值爲對象的選項,例如
methods
、components
和directives
,將被合併爲同一個對象。兩個對象鍵名衝突時,取組件對象的鍵值對。
Vue.extend
Vue.extend
屬於 Vue 的全局 API。它使用基礎 Vue 構造器,創建一個“子類”。參數是一個包含組件選項的對象。如下:
<div id="app"></div>
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White'
}
}
})
// 創建 Profile 實例,並掛載到一個元素上。
new Profile().$mount('#app')
我們常用 Vue.extend
封裝一些全局插件,比如 toast
, diolog
等。
下面以封裝一個 toast
組件爲例。
1、編寫組件
根據傳入的 type 確定彈窗的類型(成功提示,失敗提示,警告,加載,純文字)
設置彈窗消失的時間
<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
構造器把 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、在項目中調用
this.$toast({ msg: '手機號碼不能爲空' })
this.$toast({
msg: '成功提示',
type: 'success'
})
Vue.extend 和 Vue.component 的區別
component
是需要先進行組件註冊後,然後在template
中使用註冊的標籤名來實現組件的使用。Vue.extend
則是編程式的寫法。控制
component
的顯示與否,需要在父組件中傳入一個狀態來控制或者在組件外部用v-if/v-show
來實現控制,而Vue.extend
的顯示與否是手動的去做組件的掛載和銷燬。
Vue.directive
註冊或獲取全局指令。指令定義函數提供了幾個鉤子函數(可選):
bind: 只調用一次,指令第一次綁定到元素時調用,可以定義一個在綁定時執行一次的初始化動作。
inserted: 被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
update: 被綁定元素所在的模板更新時調用,而不論綁定值是否變化。通過比較更新前後的綁定值。
componentUpdated: 被綁定元素所在模板完成一次更新週期時調用。
unbind: 只調用一次, 指令與元素解綁時調用。
下面封裝一個複製粘貼文本的例子。
1、編寫指令 copy.js
const vCopy = {
bind (el, { value }) {
el.$value = value // 用一個全局屬性來存傳進來的值
el.handler = () => {
if (!el.$value) {
alert('無複製內容')
return
}
// 動態創建 textarea 標籤
const textarea = document.createElement('textarea')
// 將該 textarea 設爲 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區域
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)
},
// 當傳進來的值更新的時候觸發
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 年終總結 - 成長不及預期的 3 年之癢,可以知道爲什麼 😂
本文分享自微信公衆號 - 全棧修煉(QuanZhanXiuLian)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。