vue中router路由的使用


詳情請看

華燈初上lovl的博客

慕容小凡的博客

 

想動態綁定router

則應該是

<router-link :to="'/one/'+type">跳轉到one</router-link>使用字符串連接而不是{{type}}來綁定

 在router.js中寫入

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import one from '@/components/one'
import two from '@/components/two'
import a from '@/components/sub/a'
Vue.use(Router)

export default new Router({
    routes: [{
        path: '/',
        name: 'Hello',
        component: Hello
    }, {
        path: '/one/:type',
        name: 'one',
        component: one
    }, {
        path: '/two/:userName/:id/:loc',//后面是參數,在相應組件中使用    this.$route.params.xxx 來獲取
        name: 'two',
        component: two,
        children: [{                 //這里是路由的嵌套
            path: '/two/a',            
            name: 'a',
            component: a
        }]
    }]
})

在相應的頁面中寫入:

<template>
  <div class="hello">
      <router-link :to="'/one/'+type">跳轉到one</router-link>
      <router-link to="/two/feng/12/luzhou">跳轉到two</router-link>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      type:"les"
    }
  },
  
}
</script>

<style scoped>

</style>

即可跳轉到相應的頁面

導航的鈎子:

全局的導航鈎子

const router = new Router({...})
 // beforeEach 全局的導航鈎子   即為只要鏈接導航,都將進入此鈎子函數
router.beforeEach((to, from, next) =>{
    console.log(to)  //即將要進入的目標 路由對象
    
    console.log(from)  //當前導航正要離開的路由
    
    next() //確保要調用 next 方法,否則鈎子就不會被 resolved
})

組件內的導航鈎子:

beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    // 不!能!獲取組件實例 `this`
    // 因為當鈎子執行前,組件實例還沒被創建
  },
  beforeRouteUpdate (to, from, next) {
    // 在當前路由改變,但是該組件被復用時調用
    // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
    // 由於會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。
    // 可以訪問組件實例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 導航離開該組件的對應路由時調用
    // 可以訪問組件實例 `this`
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM