通常的url 地址由什么构成呢:协议名 域名 端口号 路径 参数 哈希值
比如::80/home/index?name=zs#absdklfajdf
当哈希值改变(哈希值就是:#absdklfajdf),页面不会发生跳转,单页面应用就是利用了这一点:
单页面应用因为只有一个页面,所以页面不能发生跳转,但是,我们又需要根据url地址来展示不同的组件
这个时候,只能用哈希值来表示究竟要展示哪个组件了
单页面应用就是根据hash值来改的
给window注册onhashchange事件,当哈希值改变时通过location.hash就能获得相应的哈希值,然后就能跳到相应的页面:
<body><div id="app"><component :is="currentPage"></component></div><script src="./node_modules/vue/dist/vue.js"></script><script>// 设计用户访问的规则// #/login 访问登录页 要给用户展示login组件// #/register 访问注册页 要给用户展示register组件// #/list 列表页 要给用户展示list组件ponent("login", {template: `<div><h1>这是登录页</h1><input type="text"><input type="text"><button>登录</button></div>`});ponent("register", {template: `<div><h1>这是注册页</h1><input type="text"><input type="text"><input type="text"><button>注册</button></div>`});ponent("list", {template: `<div><h1>这是列表页</h1><input type="text"><input type="text"><button>登录</button></div>`});const vm = new Vue({el: "#app",data: {currentPage: "login"},created() {window.onhashchange = () => {this.goPage()};},methods: {goPage() {switch (location.hash) {case "#/login":this.currentPage = "login";break;case "#/register":this.currentPage = "register";break;case "#/list":this.currentPage = "list";break;}}}});</script></body>