How to realize Vue project global configuration WeChat sharing
This time I will show you how to implement WeChat sharing of the global configuration of the Vue project, and what are the precautions for realizing the global configuration of the Vue project WeChat sharing. The following is a practical case, let's take a look.
This project is a mobile project, mainly used to access public account services. The project uses two login methods, WeChat authorized login and account and password login. For mobile projects, in order to facilitate project expansion and provide development hot update speed, the project is divided into different modules, each module is a single-page application. There are two types of pages, one that requires users to log in before they can be browsed, and the other that users can browse without logging in. No matter which one is used, WeChat sharing is configured.
Technology used
1. Use vue as the framework
2. Use vux as the UI component library
Global configuration of WeChat Sharing ideas
1. Distinguish between general and special. In general, the default sharing copy is configured globally; there are two special cases. One is that the shared content does not need to be obtained asynchronously, so in routingConfigure when jumping. The other is that the shared content needs to be obtained asynchronously, and the shared content needs to be updated after the asynchronous content is obtained.
2. For content that does not need to be obtained asynchronously, we use the method defined in the routing meta-information and directly call the public function to update the shared content after each routing jump.
For details, please check the usage instructions of WeChat JSSDK
// wxShare.js
import Vue from 'vue'
// 在组件外使用vux集成的微信jssdk
import { WechatPlugin, AjaxPlugin } from 'vux'
Vue.use(WechatPlugin)
Vue.use(AjaxPlugin)
export default function wxShare ({title, desc, timelineTitle, link, imgUrl} = {}) {
Vue.wechat.config({
debug: false,
appId: appId,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
})
Vue.wechat.ready(() => {
Vue.wechat.onMenuShareAppMessage({
title: title, // 分享标题
desc: desc || '默认分享文案', // 分享描述
link: link || window.location.href, // 分享链接
imgUrl: imgUrl || '图标地址(必须是有效的Link)' // 分享图标
})
Vue.wechat.onMenuShareTimeline({
title: timelineTitle || desc || '默认分享文案', // 分享标题,由于分享到朋友圈没有desc,所以这里采用的策略是,指定的朋友圈分享标题优先,其次采用发送给朋友的描述,最后采用默认文案。
link: link || window.location.href, // 分享链接
imgUrl: imgUrl || '图标地址(必须是有效的Link)' // 分享图标
})
})
Vue.wechat.error((res) => {
})
}
// 为Vue的原型对象添加该方法,则所有vue实例都能继承该方法
Vue.prototype.$wxShare = wxShare
// router/index.js 每个模块都有自己内部的路由配置
// codes...
const routes = [
{
path: '/index',
name: 'index',
redirect: '/index/homepage',
children: [
{
path: '/index/homepage',
name: 'homepage',
component: homepage
meta: {
title: '这是主页',
shareDesc: '这是本站的主页',
desc: 'homepage, click and see!',
timelineTitle: '这是首页,欢迎点击关注,blablablablabla~~~',
imgUrl: 'http://frankzhang.me/wp-content/uploads/2017/08/cropped-favicon-01.png'
}
},
]
}
]
// routerRule,公共路由配置,所有模块共用一个路由控制策略
import wxShare from '@/utils/wxShare'
export default function routerRule (router) {
// other codes...
router.afterEach(( to, from ) => {
wxShare({ title: to.meta.title, desc: to.meta.shareDesc, link: to.meta.shareLink, logo: to.meta.shareLogo})
})
}
// main.js
import routerRule from ...
routerRule(router)
After the above configuration, router.afterEach will call wxShare once, re-read the meta information in the router and redefine the WeChat sharing content to achieve The purpose of combining global configuration and special configuration.
Shared content that needs to be obtained asynchronously
In this case, we can use the created hook of the vue instance and call wxShare once in the successful callback of obtaining the data.
// homepage.vue
<script>
export default {
data() {
return {
}
},
created() {
getHomepageInfo()
.then( res => {
this.$wxShare({
title: res.title,
desc: res.desc,
imgUrl: res.logo
})
} )
}
}
</script>
Points to note
1. If the project adopts non-history mode, you need to remove the part after # on the URL and pass it to the backend in exchange for WeChat signature.
2. According to WeChat official instructions:
All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be able to be called (the same URL only needs to be called once, for changing URLs The SPA web app can be called every time the url changes...
Due to the SPA application, after the url changes, it needs to be reconfigured once and the configuration information of the current page is re-injected, so this step must be done in the router. Called in afterEach! Because according to the instructions of vue-router, after the navigation is confirmed, the global afterEach hook is called. At this time, the navigation has been confirmed and the url has changed. You can re-obtain the WeChat signature for the updated url.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of the steps to optimize the Vue project
How to use Koa in Node.js to implement JWT user authentication
The above is the detailed content of How to realize Vue project global configuration WeChat sharing. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.






