[vue-router] hash、history模式底层实现思想

//history.pushState附加哈希值并不会触发onhashchange
var newHash = 'test';
history.replaceState(null, null, window.location.pathname + '#' + newHash);

Hash模式底层思想

  window.onhashchange() 就会监听到哈希值改变

History模式底层思想

    可以使用浏览器前进后退功能,使用onpopstate监听浏览器前进后退

实现代码

<body>
    <button onclick="_click1()">hash模式</button>

</body>
<script>
    function _click1(){
        location.hash='test'
    }
    addEventListener('hashchange',function(){
        console.log('触发了hashchange');
    })
</script>

vue-router配置

//mode值 可以使history 可以是hash,默认是hash
const router = new VueRouter({ mode: 'history', routes: [...] })

原文地址:https://www.cnblogs.com/lv77/p/14584782.html