search
HomeWeb Front-endJS TutorialVue project global configuration WeChat sharing step instructions

This time I will bring you the step-by-step instructions for sharing the global configuration of the Vue project on WeChat. What are the precautions for sharing on WeChat for the global configuration of the Vue project? 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:

Dynamic loading of JS files three Summary of methods

JS summary of cross-domain methods that support post requests

The above is the detailed content of Vue project global configuration WeChat sharing step instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor