Vue-router(4)之路由傳參、命名路由 和 程式設計式導航
阿新 • • 發佈:2018-11-24
路由傳參
案例:現在需要展示一個電影列表頁,點選每一部電影,會跳轉到該部電影詳情頁(跳轉時攜帶type和id)
程式碼實現(未攜帶type):
index.js
import Vue from 'vue' // 1. 匯入和安裝 import VueRouter from 'vue-router' Vue.use(VueRouter) import MovieList from './MovieList.vue' import MovieDetail from './MovieDetail.vue' // 2. 建立路由物件 const router = new VueRouter({ routes: [ {path:'/', redirect: '/movielist'}, { path: '/movieist', component: MovieList }, // 在路由規則中,可以把引數項,前面新增 : // 1. 如果在元件中,想要拿到 path 中匹配的路由引數項,可以為 路由規則 開啟 props 傳參 { path: '/movie/detail/:id', component: MovieDetail, props: true } ] }) import app from './app.vue' const vm = new Vue({ el: '#app', render: c=> c(app), router // 3. 掛載路由 })
movieList.vue
<template> <div> <h3>電影列表</h3> <ul> <!-- router-link 的 to 屬性,可以使用 v-bind 屬性繫結,動態繫結一個路由地址 --> <!-- router-link 預設渲染為 a 連結,可以指定 tag 屬性,強制 router-link 渲染為特定的標籤 --> <!-- 使用字串拼接 ,得到 路由地址,實現跳轉--> <router-link tag="li" :to="'/movie/detail/' + item.id" v-for="item in movielist" :key="item.id"> {{item.id}} - {{item.type}} - {{item.name}} </router-link> </ul> </div> </template> <script> export default { data() { return { movielist: [ { id: 1, type: 'en', name: '神奇動物' }, { id: 2, type: 'cn', name: '紅海行動' }, { id: 3, type: 'jp', name: '名偵探柯南' }, { id: 4, type: 'us', name: '復仇者聯盟' } ] } } } </script> <style lang="less" scoped> ul { padding: 0; margin: 0; li { line-height: 35px; font-size: 12px; border: 1px solid #ccc; margin: 10px 0; } } </style>
movieDetails.vue
<template> <div> <h3>電影詳情頁 --- {{id}}</h3> </div> </template> <script> export default { props: ['id'], created() { console.log(this) } } </script>
命名路由(攜帶type)
命名路由就是為路由規則新增一個name屬性
1、在index.js/router下:給MovieDetails新增name屬性
const router = new VueRouter({ routes: [ // 重定向 { path: '/', redirect: '/list'}, { path: '/list', component: MovieList }, // 在路由規則中,可以把引數項,前面新增 : // 1. 如果在元件中,想要拿到 path 中匹配的路由引數項,可以為 路由規則 開啟 props 傳參 { path: '/movie/detail/:id/:type', component: MovieDetails, props: true, name: 'MovieDetail'} ] })
2、在movieList.vue下:to使用name
<router-link tag="li" :to="{name: 'MovieDetail',params:{id:item.id,type:item.type}}" v-for="item in movielist" :key="item.id"> {{item.id}} - {{item.type}} - {{item.name}} </router-link>
movieDetails.vue:
<template> <div> <h3>電影詳情頁 --- {{id}} --- {{type}}</h3> </div> </template> <script> export default { props: ['type','id'], created() { console.log(this) } } </script>
程式設計式導航
-
什麼是程式設計式導航
-
使用
vue-router
提供的JS API實現路由跳轉的方式,叫做程式設計式導航; -
a標籤屬於標籤式導航
-
-
程式設計式導航的用法
叫做路由引數式物件,router叫做路由導航式物件
-
this.$router.push('路徑的地址')
-
this.$router.go(n)
-
this.$router.forward()
-
movieDetails.vue:
<template> <div> <h3>電影詳情頁 --- {{id}} --- {{type}}</h3> <button @click="goBack()">返回上一級</button> </div> </template> <script> export default { props: ['type','id'], created() { console.log(this) }, methods: { goBack() { this.$router.go(-1) // this.$router.back() } } } </script>