vue中render渲染路由

1不带参数路由渲染(hash路由)

1.1定义三个组件

 const Foo = {template:'<div>foo</div>'}
 const Bar = {template:'<div>bar</div>'}
 const NotFound = { template: '<div>NotFound</div>' }

1.2定义路由匹配规则

  const routerTable = {
      'foo':Foo,//  为/foo跳转到Foo组件
      'bar':Bar
    }

1.3地址栏改变时监听

 window.addEventListener('hashchange',()=>{
      app.url = window.location.hash.slice(1)//app.url为Vue实例的响应数据,监听地址栏变化,并修改响应数据url
    })

1.4创建Vue实例使用render渲染

复制代码
 const app = new Vue({
      el:'#app',
      data:{
        url:window.location.hash.slice(1)
      },
      render(h){
        return h('div',[
          h(routerTable[this.url] || NotFound),//渲染路由对应的组件
          h('a',{attrs:{href:'#foo'}},'foo'),//渲染a元素,模拟路由跳转
          " | ",
          h('a', { attrs: { href: '#bar' } }, 'bar'),
        ])
      }
    })
复制代码

1.5完整代码

复制代码
 <script src="./vue.js"></script>
  <div id="app">
  </div>
  <script>

    const Foo = {template:'<div>foo</div>'}
    const Bar = {template:'<div>bar</div>'}
    const NotFound = { template: '<div>NotFound</div>' }

    const routerTable = {
      'foo':Foo,
      'bar':Bar
    }

    window.addEventListener('hashchange',()=>{
      app.url = window.location.hash.slice(1)
      console.log(app.url)
    })
    const app = new Vue({
      el:'#app',
      data:{
        url:window.location.hash.slice(1)
      },
      render(h){
        return h('div',[
          h(routerTable[this.url] || NotFound),
          h('a',{attrs:{href:'#foo'}},'foo'),
          " | ",
          h('a', { attrs: { href: '#bar' } }, 'bar'),
        ])
      }
    })
  </script>
复制代码

 

2.带参数路由跳转与解析,例如'/foo/123',通过prop传递id

2.1定义三个路由,Foo路由带有参数id

 const Foo = {
      props:['id'],
      template:`<div>foo with id {{id}}</div>`
    }
    const Bar = {template:'<div>bar</div>'}
    const NotFound = { template: '<div>NotFound</div>' }

2.2定义路由规则与解析

复制代码
  const routerTable = {//储存路由
      '/foo/:id':Foo,
      '/bar':Bar
    }

   //创建储存路由数组,预编译
    const compileRouters = []
    Object.keys(routerTable).forEach(path=>{
      const dynamicSegments=[]
      const regex = pathToRegexp(path,dynamicSegments)//pathToRegexp将路径解析为正则和获取参数id名
      const component = routerTable[path]
      compileRouters.push({
        component,regex,dynamicSegments
      })
    })
 
复制代码

2.3地址栏改变时监听

 window.addEventListener('hashchange',()=>{
      app.url = window.location.hash.slice(1)//app.url为Vue实例的响应数据,监听地址栏变化,并修改响应数据url
    })

2.4Vue实例渲染

复制代码
 const app = new Vue({
      el:'#app',
      data:{
        url:window.location.hash.slice(1)//响应式路由地址
      },
      render(h){
        const path ='/'+ this.url
        //需要渲染的组件
        let componentToRender
        //传递参数
        let props = {}

        compileRouters.some(router=>{//some匹配到就结束
          const match = router.regex.exec(path)//匹配当前路径
          if(match){//如果存在
            componentToRender = router.component//当前需要渲染的路由
            router.dynamicSegments.forEach((segment,index)=>{
              props[segment.name] = match[index+1]//需要传递的参数
            })
          }
        })

        return h('div',[
          h(componentToRender || NotFound,{props}),
          h('a',{attrs:{href:'#foo/123'}},'foo123'),
           " | ",
          h('a', { attrs: { href: '#foo/234' } }, 'foo234'),
          " | ",
          h('a', { attrs: { href: '#bar' } }, 'bar'),
        ])
      }
    })
复制代码

2.5完整代码

复制代码
<script src="./vue.js"></script>
<script src="./pathtoregexp.js"></script>//引入路由解析工具
  <div id="app">
  </div>
  <script> 

    const Foo = {
      props:['id'],
      template:`<div>foo with id {{id}}</div>`
    }
    const Bar = {template:'<div>bar</div>'}
    const NotFound = { template: '<div>NotFound</div>' }

    const routerTable = {//储存路由
      '/foo/:id':Foo,
      '/bar':Bar
    }
    
    //创建储存路由数组,预编译
    const compileRouters = []
    Object.keys(routerTable).forEach(path=>{
      const dynamicSegments=[]
      const regex = pathToRegexp(path,dynamicSegments)//pathToRegexp将路径解析为正则和获取参数id名
      const component = routerTable[path]
      compileRouters.push({
        component,regex,dynamicSegments
      })
    })

    window.addEventListener('hashchange',()=>{//获取当前页面hash路由
      app.url = window.location.hash.slice(1)
    })
    const app = new Vue({
      el:'#app',
      data:{
        url:window.location.hash.slice(1)//响应式路由地址
      },
      render(h){
        const path ='/'+ this.url
        //需要渲染的组件
        let componentToRender
        //传递参数
        let props = {}

        compileRouters.some(router=>{//some匹配到就结束
          const match = router.regex.exec(path)//匹配当前路径
          if(match){//如果存在
            componentToRender = router.component//当前需要渲染的路由
            router.dynamicSegments.forEach((segment,index)=>{
              props[segment.name] = match[index+1]//需要传递的参数
            })
          }
        })

        return h('div',[
          h(componentToRender || NotFound,{props}),
          h('a',{attrs:{href:'#foo/123'}},'foo123'),
           " | ",
          h('a', { attrs: { href: '#foo/234' } }, 'foo234'),
          " | ",
          h('a', { attrs: { href: '#bar' } }, 'bar'),
        ])
      }
    })
  </script>
复制代码

 

posted @   lijun12138  阅读(466)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示