uniapp-vue3語法實現(xiàn)小程序全局分享(setup,mixin)
隨著vue3的普及uniapp官方也支持了vue3語法的編寫
相信大家在開發(fā)過程中肯定碰到過小程序所有頁面都要開啟分享功能的需求;指定的頁面(如:文章詳情頁)有單獨的配置,而非單獨配置的頁面(如:付費的訂單詳情頁)都是統(tǒng)一跳轉到首頁
我的做法如下:
1. 創(chuàng)建share.js
// utils/share.js
export default {
onLoad(){ // 創(chuàng)建時設置統(tǒng)一頁面的默認值
uni.$mpShare = {
title: 'xxxx',
desc: 'yyyy',
path: '/pages/tabList/index',
imageUrl: 'https://zzzzzzz.com/images/fx.jpg'
}
},
onShareAppMessage() { //發(fā)送給朋友
console.log(uni.$mpShare);
return uni.$mpShare
},
onShareTimeline() { //分享到朋友圈
return uni.$mpShare
},
onUnload(){ // 關閉頁面時重置
uni.$mpShare = {
title: 'xxxx',
desc: 'yyyy',
path: '/pages/tabList/index',
imageUrl: 'https://zzzzzzz.com/images/fx.jpg'
}
}
};
2. main.js引入share.js文件
// main.js
import App from './App'
import {
createSSRApp
} from 'vue'
import share from '/utils/share' // 引入share.js
export function createApp() {
const app = createSSRApp(App)
app.mixin(Share) // 使用mixin全局混入
uni.$u.config.unit = 'rpx'
return {
app
}
}
此時小程序所有頁的分享功能都打開并且都統(tǒng)一跳轉到首頁分享的圖片也是統(tǒng)一的文章來源:http://www.zghlxwxcb.cn/news/detail-810662.html
3. 修改需要單獨配置分享的頁面
// pages/news/news.vue
<script setup>
import { computed, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { Get_newsDetails } from '../../config/api'; // 文章詳情接口
const detail= reactive({}); // 文章詳情
const shareData = computed(()=>{ // 分享的數(shù)據(jù)
return {
title: data.detail.title,
desc: data.detail.title,
path: '/pages/news/detail?id=' + data.detail.id,
imageUrl: data.detail.cover
}
})
async function getDetail() { // 獲取新聞詳情
const res = await Get_newsDetails({
id: data.id
});
detail.value = res.data
}
onLoad(async (options) => {
data.id = options.id;
await getDetail();
uni.$mpShare = shareData.value // 修改uni.$mpShare的值
});
onShow(()=>{
uni.$mpShare = shareData.value // 修改uni.$mpShare的值
})
</script>
在頁面你想要修改的地方修改uni.$mpShare的值就可實現(xiàn)差異化, 上面代碼在頁面onLoad時會將其設置為初始的統(tǒng)一頁面的值,并且在頁面onUnload時也會被設置為初始的統(tǒng)一頁面文章來源地址http://www.zghlxwxcb.cn/news/detail-810662.html
到了這里,關于uniapp-vue3語法實現(xiàn)小程序全局分享(setup,mixin)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!