在Vue中具有Mixin 混入屬性
mixins 選項(xiàng)接收一個(gè)混入對象的數(shù)組。這些混入對象可以像正常的實(shí)例對象一樣包含實(shí)例選項(xiàng),這些選項(xiàng)將會(huì)被合并到最終的選項(xiàng)中,使用的是和 Vue.extend() 一樣的選項(xiàng)合并邏輯。也就是說,如果你的混入包含一個(gè) created 鉤子,而創(chuàng)建組件本身也有一個(gè),那么兩個(gè)函數(shù)都會(huì)被調(diào)用。
Mixin 鉤子按照傳入順序依次調(diào)用,并在調(diào)用組件自身的鉤子之前被調(diào)用。
Vue官方介紹
- 示例
var mixin = {
created: function () { console.log(1) }
}
var vm = new Vue({
created: function () { console.log(2) },
mixins: [mixin]
})
// => 1
// => 2
看完介紹,就進(jìn)入正題,如何實(shí)現(xiàn)頁面的全局注冊分享?
此案例使用uni-app進(jìn)行演示,小程序和Vue同樣適用。
- 根目錄main.js
-
onShareAppMessage(OBJECT)
小程序中用戶點(diǎn)擊分享后,在 js 中定義 onShareAppMessage 處理函數(shù)(和 onLoad 等生命周期函數(shù)同級(jí)),設(shè)置該頁面的分享信息。
用戶點(diǎn)擊分享按鈕的時(shí)候會(huì)調(diào)用。這個(gè)分享按鈕可能是小程序右上角原生菜單自帶的分享按鈕,也可能是開發(fā)者在頁面中放置的分享按鈕;
此事件需要 return 一個(gè)Object,用于自定義分享內(nèi)容。
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'
// 條件編譯,只有微信小程序的時(shí)候執(zhí)行
// #ifdef MP-WEIXIN
Vue.mixin({
onLoad() {
// 掛載個(gè)分享對象,供頁面具體配置,默認(rèn)的分享對象。
this.$share={
title:'',
patch:'',
desc:''
}
},
// 微信小程序點(diǎn)擊分享事件
onShareAppMessage(res) {
if(res.from==='button')return // 判斷分享來自的類型
return {
title:this.$share.title,
content:this.$share.desc
}
}
})
// #endif
const app = new Vue({
...App
})
app.$mount()
簡單配置以后就可以在頁面直接使用。
頁面使用
onLoad() {
this.$share.title='分享標(biāo)題'
this.$share.desc="測試分享描述"
}
分享出去之后

總結(jié)
通過Mixin一步操作就可以實(shí)現(xiàn)全局分享的方法,mixin還有更多用法(全局的scoket通訊等等)更多的功能等待大家一起發(fā)現(xiàn)。
最后,喜歡文章的別忘記點(diǎn)一下小心心~