vue 路由功能

目录:

vue 路由

整合第三方路由

--------------------------------

对于大多数单页面应用,都推荐使用官方支持的vue-router库。更多细节可以看vue-router文档。

如果只需要非常简单的路由而不需要引入整个路由库,可以动态渲染一个页面级的组件:

demo:

<h4>使用 h5 实现前端路由</h4>
  <ul>
    <li> <a  onclick="home()">首页</a></li>
    <li> <a  onclick="message()">消息</a></li>
    <li> <a  onclick="mine()">我的</a></li>
  </ul>
  <div id="showContent" style="height:240px;width:200px;background-color:red">
    home
  </div>

  <script type="text/javascript">

    function home() {
      // 添加到历史记录栈中
      history.pushState({name:'home',id:1},null,"?page=home#index")
      showCard('home')
    };

    function message() {
      history.pushState({name:'message',id:2},null,"?page=message#haha")
      showCard('message')
    }

    function mine(){
      history.pushState({
        id:3,
        name:'mine'
      },null,"?name=tigerchain&&sex=man")
      showCard('mine')
    }

整合第三方路由:

hash路由:

demo:

  <script type="text/javascript">
  //自定义一个路由规则
  function CustomRouter(){
   this.routes = {};
   this.curUrl = '';

   this.route = function(path, callback){
       this.routes[path] = callback || function(){};
   };

   this.refresh = function(){
         if(location.hash.length !=0){ // 如果 hash 存在
           this.curUrl = location.hash.slice(1) || '/';
           if(this.curUrl.indexOf('/')!=-1){ //这里粗略的把 hash 过滤掉
               this.routes[this.curUrl]();
           }
         }
   };

   this.init = function(){
       window.addEventListener('load', this.refresh.bind(this), false);
       window.addEventListener('hashchange', this.refresh.bind(this), false);
   }
  }

还有一种vue -cli 的路由:

// 定义一个 Mine 组件

  var Mine = Vue.extend({
    data() {
      return {
        title:'我的界面',
      }
    },
    template:'<div style="height:100px;width:100px;background:orange">'+
                '<span>{{title}}--取得路由参数:{{$route.params.id}}</span>'+
             '</div>'
  })

  // 声明路由规则
  const routes = [
    //给一个默认的路由,默认显示 Main 组件
    {
      path:'/',component:Main
    },
    {
      path:'/main',component:Main
    },
    {
      path:'/message',component:Message
    },
    {
      path:'/mine/:id',component:Mine
    }
  ]

  // 全局注册组件 组件的别名要是小写,否则会报错
  // Vue.component('home', Main)
  // Vue.component('message', Message)
  // Vue.component('mine', Mine)

  // 创建 router 实例
  const router = new VueRouter({
    routes // 就相当于是 routes:routes
  })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值