首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >vue单页面应用的原理

vue单页面应用的原理

作者头像
全栈程序员站长
发布2022-09-07 16:07:29
发布2022-09-07 16:07:29
8890
举报

大家好,又见面了,我是你们的朋友全栈君。

通常的url 地址由什么构成呢:协议名 域名 端口号 路径 参数 哈希值

比如:http://www.itcast.cn:80/home/index?name=zs#absdklfajdf

当哈希值改变(哈希值就是:#absdklfajdf),页面不会发生跳转,单页面应用就是利用了这一点:

单页面应用因为只有一个页面,所以页面不能发生跳转,但是,我们又需要根据url地址来展示不同的组件 这个时候,只能用哈希值来表示究竟要展示哪个组件了 单页面应用就是根据hash值来改的

给window注册onhashchange事件,当哈希值改变时通过location.hash就能获得相应的哈希值,然后就能跳到相应的页面:

代码语言:javascript
复制
<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组件

      Vue.component("login", {
        template: `<div>
          <h1>这是登录页</h1>
          <input type="text"><input type="text"><button>登录</button>
        </div>`
      });

      Vue.component("register", {
        template: `<div>
          <h1>这是注册页</h1>
          <input type="text"><input type="text"><input type="text"><button>注册</button>
        </div>`
      });

      Vue.component("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>

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148496.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档