Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue指令,根据路由动态改变title #34

Open
JesseZhao1990 opened this issue Jan 17, 2018 · 0 comments
Open

Vue指令,根据路由动态改变title #34

JesseZhao1990 opened this issue Jan 17, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

背景

由于微信里面的页面,微信的标题是取html的header中的title,产品让做动态title。而且微信里还有个bug,在ios系统中,无法直接给document的title赋值。so,搞个指令吧。

/**
 * 给header的title赋值的指令
 * 注意,此指令只需要在app.vue中使用一次即可。别处不再需要使用
 * @param {*} Vue
 */

function install(Vue) {
  function setTitle(el, binding) {
    const title = binding.value;
    const img = el.getAttribute('img') || '';

    if (typeof title === 'undefined' || window.document.title === title) {
      return;
    }
    document.title = title;
    // 由于微信的bug导致直接给document.title赋值无效,所以如果是ios系统,则利用iframe的方式去改变title
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';

      iframe.setAttribute('src', img || '');

      const iframeCallback = () => {
        setTimeout(() => {
          iframe.removeEventListener('load', iframeCallback);
          document.body.removeChild(iframe);
        }, 0);
      };

      iframe.addEventListener('load', iframeCallback);
      document.body.appendChild(iframe);
    }
  }

  Vue.directive('header-title', {
    bind: setTitle,
    update: setTitle,
  });
}


export default {
  install,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant