H5页面在手机QQ和QQ空间内分享时,分享出去的只有链接,没有摘要和缩略图,使用微信的JS-SDK并没有得到想要的效果,后来查资料,看到有人通过给H5页面设置meta标签实现了这一功能;需要设置的meta标签如下:
<meta itemprop="name" content="网页标题">
<meta itemprop="description" content="网页描述">
<meta itemprop="image" content="缩略图">
后来自己尝试,发现这样确实可以达到想要的效果,可是问题是我的项目是基于vue-cli开发的,并且,我要分享的文章内容是动态获取的,这就需要动态的设置摘要和缩略图,后来,我找到了动态设置meta标签的方法;需要借助vue-mate来实现;具体步骤如下:
1. 安装vue-mate
npm install vue-meta --save
2.在main.js引入
import Meta from 'vue-meta'
Vue.use(Meta)
3.为需要分享的页面meta
export default {
metaInfo: {
title: 'This is the test',
meta: [
{ itemprop: 'name', content: this.shareTitle },
{ itemprop: 'image', content: this.shareImg },
{ name: 'description',itemprop:"description", content: this.shareDesc||this.shareUrl }
]
}
}
另外,使用异步请求的信息设置mate时,可使用 metaInfo()
方法。
<template>
<div>
<h1>{{{ shareTitle }}}</h1>
</div>
</template>
<script>
export default {
name: 'post',
data () {
return {
shareTitle : '',
shareImg :'',
shareDesc: ''
}
},
metaInfo () {
return {
meta: [
{ itemprop: 'name', content: this.shareTitle },
{ itemprop: 'image', content: this.shareImg },
{ name: 'description',itemprop:"description", content: this.shareDesc||this.shareUrl },
]
}
},
created () {
this.initData()
},
methods: {
initData () {
axios.get('some/url').then((resp) => {
// 设置title时 metaInfo 会同时更新
this.shareTitle = resp.title
this.shareImg=resp.img;
this.shareDesc= resp.decription
})
}
}
}
</script>