您當前位置: 南順網絡>> 官方資訊>> 建站知識

和尤雨溪一起進階vue

1 初級版

借助vue的動態組件,可以實現一個簡單的路由功能,如下

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> 
<div id="app">     
    <a href="#foo">foo</a>     
    <a href="#bar">bar</a>     
    <component :is="url"></component> 
</div> 
<script>     
// 這是一個比較簡單的解決方案,但是有一個問題,初始化的時候無法匹配  
   window.addEventListener('hashchange', () => {         
       app.url = window.location.hash.slice(1)     
    });    
    let app = new Vue({       
      el: '#app',         
      data() {          
         return {              
            url: null             
            }        
         },         
       components: {         
           foo: {template: `<div>foo-component</div>`},             
           bar: {template: `<div>bar-component</div>`}        
         }     }) 
 </script>

2 改進版

解耦微改進一下,將路由提取到一個路由表中,

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> 
<div id="app"> </div> 
<script> 
    const Foo = {template: '<div>foo</div>'} 
    const Bar = {template: '<div>bar</div>'} 
    const NotFound = {template: '<div>not found</div>'} 
    // 在對象里面統一配置路由 
    const routeTable = {     'foo': Foo,     'bar': Bar }
     window.addEventListener('hashchange', () => {     app.url = window.location.hash.slice(1) }) 
     let app = new Vue({     
         el:'#app',         
         data() {         
             return {            
                  url: window.location.hash.slice(1)         
               }  },        
         render(h) {          
            return h('div', [             
                h('a', {attrs: {href: '#foo'}}, 'foo'),            
                     '|',               
                       h('a', {attrs: {href: '#bar'}}, 'bar'),                
                       h(routeTable[this.url] || NotFound),           
                         ])        
                          } })
 </script>

3 最終版

上面都是處理簡單的url, 實際開發的時候,配置的路由都是多頁面,多組件,路由的path也會比較長,如/a/b, /a/b/c, 還有動態路由,比如/a/:id,這個時候上面的方法就不能準確匹配了, 如果你是正則達人,你可以自己試試解析這些復雜的path,不是的話就使用別人封裝好的第三方庫吧,這里推薦path-to-regexp, 這個庫的作用作者一句話就概述完了:

Turn a path string such as/user/:nameinto a regular expression

大家可以點進去鏈接了解一下用法,這里我們介紹接下來要用的部分

const keys = [] const regexp = pathToRegexp('/foo/:id', keys) // regexp = /^\/foo\/((?:[^\/]+?))(?:\/(?=$))?$/i // keys = [{ delimiter: "/", name: "id", optional: false, partial: false, pattern: "[^\/]+?", prefix: "/", repeat: false}] // 得到了正則表達式regexp, 傳入實際的url執行正則的exec方法 // 不匹配 const match1 = regexp.exec('/test/route'); // null const match3 = regexp.exec('/foo');        // null // 匹配 const match2 = regexp.exec('/foo/fooId'); // ["/foo/fooId", "fooId", index: 0, input: "/foo/fooId", groups: undefined] 復制代碼

ok, 我們可以解析path了,來看看接下來如何實現

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> 
// 這里是下載到本地同目錄引入的 
<script src='./path-to-regexp.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>not found</div>`   
        }     
     const routeTable = {         '/foo/:id': Foo,         '/bar': Bar,     }    
      // 處理路由     
      const compiledRoutes = [];     
      Object.keys(routeTable).forEach(path => {      
         const dynamicSegments = []         
         const regex = pathToRegexp(path, dynamicSegments)         
         const component = routeTable[path]         
         compiledRoutes.push({         
             component,             
             regex,             
             dynamicSegments        
          })     })     
          window.addEventListener('hashchange', () => {      
             app.url = window.location.hash.slice(1);     
            })     
            const app = new Vue({      
               el: '#app',         
               data() {         
                   return {             
                       url: window.location.hash.slice(1)           
                         }        
                          },        
             // 渲染那個路由,路由屬性         
             render(h) {         
                 const url = '/' + this.url             
                 let componentToRender             
                 let props = {}             
                 compiledRoutes.some(route => {              
                    const match = route.regex.exec(url)                 
                    if (match) {                
                         componentToRender = route.component                     
              // 上一步已經可以匹配到url對應的組件了                   
              // 這里多做一步,獲取動態id作為props的屬性傳入組件                     
              route.dynamicSegments.forEach((segment,index) => {                     
                  props[segment.name] = match[index+1]                    
                   })                
                    }           
                      })            
               return h('div', [             
                   h('a', { attrs: { href: '#foo/123' } }, 'foo123'),                
                    '|',                
                     h('a', { attrs: { href: '#foo/234' } }, 'foo234'),                 
                     '|',                 
                     h('a', { attrs: { href: '#bar' } }, 'bar'),                
                     h(componentToRender || NotFound, { props })            
                    ])       
                    } 
                     }) 
              </script>




編輯:--史志成

龙王捕鱼上分期下分期