Vue dynamically changes the title-vue-wechat-title component

In the hybrid application with h5 embedded in the app, the title in the webview of some apps under the iOS system cannot be modified by document.title = xxx. The reason is that the title of the webpage in the IOS webview is only loaded once, and dynamic changes are invalid.

Solve the problem that the app is embedded with h5 and ios cannot get the title

1. Installation

npm install vue-wechat-title --save

2. Use

  •  Introduced in main.js
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
  • Add meta object configuration title in router>index.js
const router = new Router({
 
  routes: [
    ...
    {
      path: "/homeIndex", 
      name: 'homeIndex',
      component: resolve => import('@/pages/home/index'),
      meta:{
        title: '主页'
      }
    },
    ...
 
 ]
});
 
router.afterEach(route => {
  // 从路由的元信息中获取 title 属性
  if (route.meta.title) {
    document.title = route.meta.title;
    // 如果是 iOS 设备,则使用如下 hack 的写法实现页面标题的更新
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      const hackIframe = document.createElement('iframe');
      hackIframe.style.display = 'none';
      hackIframe.src = '/static/html/fixIosTitle.html?r=' + Math.random();
      document.body.appendChild(hackIframe);
      setTimeout(_ => {
        document.body.removeChild(hackIframe)
      }, 300)
    }
  }
});
 
export default router;
  • Modify router-view in App.vue
<router-view v-wechat-title='$route.meta.title'></router-view>

 

Guess you like

Origin blog.csdn.net/yuan_jlj/article/details/108864131