安装weixin-js-sdk插件
npm install weixin-js-sdk
1.nuxtjs的plugins中新建 share.js
2.nuxt.config.js中配置
3.share.js文件的内容
let wx = {}
if (process.client) {
wx = require('weixin-js-sdk')
}
// import wx from 'weixin-js-sdk'; // 微信sdk依赖
// import axios from '@/libs/api.request'
import axios from 'axios'
// console.log(axios)
// 引用全局
/* eslint-disable */
const jsApiList = [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'hideOptionMenu',
'showOptionMenu',
'shareTimeline' //不存在
];
// 要用到微信API
function getJSSDK(url, dataForWeixin) {
// 调用后台接口换取参数
axios.post('/rzdb/cms/wechat/getSignature', {
url: url.url, //url 如果写的是固定的值的话,分享之后在分享会报错
timestamp: url.timestamp,
nonceStr: url.nonceStr
}, {
transformRequest: [function (data) {
let ret = '';
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
}
ret = ret.substring(0, ret.length - 1);
return ret;
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res1) => {
// console.log(res)
let res = res1.data
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.appId, // 必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.nonceStr, // 必填,生成签名的随机串
signature: res.signature, // 必填,签名
jsApiList, // 必填,需要使用的JS接口列表
});
wx.ready(() => {
wx.onMenuShareAppMessage({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) { },
success: function success(res) {
console.log('已分享');
},
cancel: function cancel(res) {
console.log('已取消');
},
fail: function fail(res) {
console.log(JSON.stringify(res), 123456);
},
});
// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareTimeline({
title: dataForWeixin.title,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
// alert('用户点击分享到朋友圈');
},
success: function success(res) {
// alert('已分享');
},
cancel: function cancel(res) {
// alert('已取消');
},
fail: function fail(res) {
alert(JSON.stringify(res));
},
});
// 2.3 监听“分享到QQ”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareQQ({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
// alert('用户点击分享到QQ');
},
complete: function complete(res) {
alert(JSON.stringify(res));
},
success: function success(res) {
// alert('已分享');
},
cancel: function cancel(res) {
// alert('已取消');
},
fail: function fail(res) {
// alert(JSON.stringify(res));
},
});
// 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareWeibo({
title: dataForWeixin.title,
desc: dataForWeixin.desc,
link: dataForWeixin.linkurl,
imgUrl: dataForWeixin.img,
trigger: function trigger(res) {
// alert('用户点击分享到微博');
},
complete: function complete(res) {
// alert(JSON.stringify(res));
},
success: function success(res) {
// alert('已分享');
},
cancel: function cancel(res) {
// alert('已取消');
},
fail: function fail(res) {
// alert(JSON.stringify(res));
console.log(JSON.stringify(res));
},
});
});
wx.error((res) => {
console.log(`${JSON.stringify(res)}微信验证失败`, 456);
// alert(JSON.stringify(res)+"微信验证失败");
});
});
}
export default {
// 获取JSSDK
getJSSDK,
};
4.文章页面中使用:newsDetail.vue
<template>
<div>
<v-row>
<!-- 新闻详情 -->
<v-col cols="12" sm="9" md="9" lg="9" style="position: relative;">
<div style=" position: relative;right: -20px;bottom: -10px; float: right; transform: scale(0.8);">
<share :fileUrl="detail.fileUrl" :newsId="detail.id"></share>
</div>
......
</v-col>
</v-row>
</div>
</template>
<script>
import Share from "../components/carousel/share.vue";
import sdk from "@/plugins/share.js"; // 引入sdk.
export default {
name: "NewsDetail",
head() {
return {
title: this.detail.title === undefined ? "融中财经" : this.detail.title,
meta: [
{
vmid: "description",
name: "description",
content: this.detail.description,
},
{ vmid: "keywords", name: "keywords", content: this.detail.keywords },
],
};
},
components: {
Share,
newsHot
},
data() {
return {
logo_wx: require('../static/images/logo_wx.jpg'),
};
},
async asyncData(app) {
let searchForm = {
// 搜索框初始化对象
pageNumber: 1, // 当前页数
pageSize: 4, // 页面大小
sort: "publishDate", // 默认排序字段
order: "desc", // 默认排序方式
isGroup: 0,
catName: "",
status: 1,
hideFlag: 0,
};
let afterId = 0;
let afterTitle = "";
let infrontId = 0;
let infrontTitle = "";
let detail = [];
let tags = [];
var content = "";
let { id } = app.route.params
let res = await app.$queryNewsDetailById({
id,
isGroup: 0,
language: 1,
status: 1,
})
if (res.success && res.result) {
// if (res.result.rzcj_news == null) return;
detail = res.result.rzcj_news;
content = res.result.rzcj_news.content;
detail.title = HTMLEncode(detail.title);
content = HTMLEncode(content);
if (res.result.rzcj_news.hotlinkFlag == 1) {
content = addKewordLink(content);
}
content = content.replace(
/text-align:left/g,
"text-align:justify"
);
if (detail.tags != null && detail.tags !== "")
tags = detail.tags.split("|");
searchForm.catName = detail.catName;
afterId = res.result.afterId == null ? 0 : res.result.afterId;
afterTitle =
res.result.afterTitle == null ? "无" : res.result.afterTitle;
infrontId =
res.result.infrontId == null ? 0 : res.result.infrontId;
infrontTitle =
res.result.infrontTitle == null ? "无" : res.result.infrontTitle;
}
let newsList = [];
let res_list = await app.$getNewsList(searchForm)
if (res_list.success) {
newsList = res_list.result.content;
}
await app.$addClicks(id)//统计点击次数接口
return {
newsList,
detail,
afterId,
afterTitle,
infrontId,
infrontTitle,
tags,
content
};
},
mounted() {
if (process.browser) {
this.getSignature()
}
},
methods: {
getSignature() {
let createNonceStr = Math.random().toString(36).substr(2, 15)
let createTimeStamp = parseInt(new Date().getTime() / 1000) + '';
const url = {
url: location.href, //url 如果写的是固定的值的话,分享之后在分享会报错
timestamp: createTimeStamp,
nonceStr: createNonceStr
}
const dataForWeixin = {
title: this.detail.title, // 分享标题
desc: this.detail.description, // 分享内容
linkurl: location.href, // 分享链接
//img: 'http://h5.thecapita.com.cn/images/logo_wx1.jpg', // 分享内容显示的图片(图片必须是正方形的链接)
img1: this.detail.picUrl, // 分享内容显示的图片(图片必须是正方形的链接)
};
// console.log(dataForWeixin)
// sdk.getJSSDK(url, dataForWeixin); //传入sdk.js需要的参数
const ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
sdk.getJSSDK(url, dataForWeixin); //传入sdk.js需要的参数
} else {
console.log('不是微信浏览器')
}
},
},
};
</script>
<style lang="scss" scoped>
.author {
margin-left: 20px;
}
.news-content {
p {
font-size: 20px !important;
}
span {
text-align: justify !important;
}
}
.copyRight {
padding: 1rem;
font-size: 14px;
margin-top: 20px;
background-color: #f2f2f2;
line-height: 30px;
}
</style>
安装qrcode2 自动生成二维码
plugins文件夹中新建qrCode.js
import Vue from 'vue'
const VueQrcode = require('qrcode2')
Vue.prototype.$QRCode = VueQrcode;
share.vue 自动生成分享二维码
<template>
<div class="text-h5 share-box">
<div class="icons_"><v-icon color="#2e2e2e" @click="share('weixin')">mdi-wechat</v-icon></div>
<!-- <div class="icons_"><v-icon color="#2e2e2e" @click="share('weixin')">mdi-share-variant </v-icon></div> -->
<div class="icons_"><v-icon color="#2e2e2e" @click="share('sina')">mdi-sina-weibo</v-icon></div>
<div class="icons_"><v-icon color="#2e2e2e" @click="share('qzone')">mdi-qqchat</v-icon></div>
<div class="icons_" v-if="fileUrl&&fileUrl.indexOf('http://')!=-1">
<v-btn class="share" cir tile width="40" min-width="40" height="40" :loading="file_loading" text depressed
@click="downLoad({id:newsId}) ">
<img style="height:20px;" src="@/static/images/icons/downLoad.png" />
</v-btn>
</div>
<!-- <div v-show="showCode">
<qr-code @closeCode="closeCode"></qr-code>
</div> -->
<v-dialog v-model="showCode" width="500">
<v-card>
<v-card-title color="red" class="text-h5 code_title ">
<span>分享到微信朋友圈</span>
<v-btn icon color="primary" x-large style="position: absolute; right: 0; top: 0;" @click="showCode=false">
<v-icon color="#fff">mdi-close</v-icon>
</v-btn>
</v-card-title>
<v-card-text>
<qr-code @closeCode="closeCode"></qr-code>
</v-card-text>
<!-- <v-divider></v-divider> -->
<div class="weixin_info">
打开微信,点击底部的“发现”,<br />使用“扫一扫”即可将网页分享至朋友圈。
</div>
</v-card>
</v-dialog>
<!-- <v-btn icon large>
<v-icon large color="primary" @click="share('qq')">mdi-chat-processing</v-icon>
</v-btn> -->
</div>
</template>
<script>
import qrCode from "./qrCode.vue";
import { mapMutations, mapState } from "vuex";
export default {
name: "share",
components: {
qrCode,
},
props: {
fileUrl: {
type: String,
default: '',
},
newsId: {
type: Number,
},
},
data() {
return {
items: [],
showCode: false,
file_loading: false,
};
},
mounted() { },
computed: {
hasLogged() {
return this.$store.state.token !== "";
}
},
methods: {
...mapMutations(["setLoginShow"]),
closeCode(val) {
this.showCode = val;
},
clickBtns() {
this.setLoginShow(true);
},
downLoad(params) {
if (!this.hasLogged) {
this.clickBtns()
return
}
this.file_loading = true
this.$getDownloadReport(params).then(res => {
// console.log(res)
if (res.data.type) {
let disposition = decodeURI(res.headers['content-disposition'])
// 从响应头中获取文件名称
let fileName = disposition.split(';')[1].split('=')[1]
// 文件下载
const blob = new Blob([res.data], {
type: "application/pdf"
});
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', `${fileName}`);
link.click();
link = null;
this.file_loading = false
this.$message.success('下载成功');
} else {
// 返回json
this.$message.warning('下载失败');
}
});
},
share(type) {
if (process.browser) {
if (type == "weixin") {
this.showCode = true;
}
//qq空间分享接口
if (type == "qzone") {
window.open(
"https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey? url=" +
document.location.href +
"?sharesource=qzone&title=标题&pics=图片地址&summary= 描述"
);
}
//新浪微博接口的传参
if (type == "sina") {
window.open(
"http://service.weibo.com/share/share.php?url=" +
document.location.href +
"?sharesource=weibo&title=标题&pic=图片&appkey=微博平台申请的key"
);
}
//qq好友接口的传参
if (type == "qq") {
window.open(
"http://connect.qq.com/widget/shareqq/index.html?url=" +
document.location.href +
"?sharesource=qzone&title=标题&pics=图片地址&summary= 描述"
);
}
}
//微信分享
// var url = window.location.href,
// encodePath = encodeURIComponent(url),
// targetUrl = 'http://qr.liantu.com/api.php?text=' + encodePath;
// window.open(url, 'weixin', 'height=320, width=320')
},
},
};
</script>
<style lang="scss" >
.share-box {
height: 50px;
display: flex;
justify-content: center;
.icons_ {
float: left;
width: 40px;
height: 40px;
line-height: 34px;
text-align: center;
background-color: #e6e6e6;
color: #fff;
margin: 0 15px;
border-radius: 50%;
// opacity: 0.8;
overflow: hidden;
&:hover {
background-color: #ac383b;
// opacity: 1;
cursor: pointer;
}
}
.icons_:hover {
background-color: #ac383b;
.v-icon {
color: #fff !important;
}
}
.share {
text-align: center;
.icon {
margin-left: 5px;
}
}
}
.weixin_info {
height: 80px;
padding: 10px;
background-color: #eee;
text-align: center;
line-height: 30px;
}
.code_title {
background: #ca091b;
position: relative;
color: #fff;
}
</style>
qrcode.vue 二维码生成页面
<template>
<div id="WX">
<div class="bd_weixin_popup_head">
<!-- <span>分享到微信朋友圈</span>
<a class="bd_weixin_popup_close" @click="close">×</a> -->
<div class="item" id="qrcode" ref="qrCode" xss="removed">
<img class="code" :src="url" alt="" />
</div>
<!-- <div class="bd_weixin_popup_foot">
打开微信,点击底部的“发现”,<br />使用“扫一扫”即可将网页分享至朋友圈。
</div> -->
</div>
</div>
</template>
<script>
export default {
name: "qrCode",
data() {
return {
QRCodeMsg: "",
url: "",
dialog: false,
};
},
mounted() {
if (process.browser) {
this.crateQrcode();
}
},
methods: {
close() {
this.$emit("closeCode", false);
},
crateQrcode() {
this.imgVisible = true;
var path = window.location.href; //获取页面的链接
this.$nextTick(() => {
let qr = new this.$QRCode.default(this.$refs.qrCode, {
width: 150,
height: 150, // 高度
render: "canvas", // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
errorCorrectionLevel: "H", //容错级别
type: "image/png", //生成的二维码类型
quality: 0.3, //二维码质量
margin: 12, //二维码留白边距
text: path,
// text: "http://www.xxx.com",//二维码内容
color: {
dark: "#333333", //前景色
light: "#fff", //背景色
},
});
this.url = path;
// qr.toDataURL('自定义的内容,可传参')
// .then(url => {
// this.url = url
// })
// .catch(err => {
// console.error(err)
// })
});
},
},
watch: {},
};
</script>
<style scoped>
#WX {
width: 290px;
/* background: red; */
padding: 10px;
background: #fff;
/* border: solid 1px #d8d8d8; */
margin: auto;
/* position: absolute;
z-index: 999;
right: 0%; */
}
.bd_weixin_popup_head {
text-align: center;
}
.bd_weixin_popup_head span {
font-size: 18px;
font-weight: bold;
line-height: 16px;
}
.bd_weixin_popup_close {
width: 20px;
height: 20px;
text-decoration: none;
font-size: 30px;
text-align: right;
position: absolute;
right: 10px;
top: 0;
cursor: pointer;
}
.bd_weixin_popup_foot {
font-size: 14px;
text-align: left;
line-height: 22px;
color: #666;
}
#weixin {
width: 185px;
height: auto;
margin: 10px auto;
}
.item {
width: 100%;
}
#qrcode {
width: 150px;
text-align: center;
margin: 0 auto;
/* position: relative;
left: 50%;
transform: translateX(-28%);
margin-top: 20px;
margin-bottom: 20px; */
}
</style>