一. 通過Vue CLI 快速創(chuàng)建一個項目
-
vue create router-demo1在終端中執(zhí)行指令 - 選擇手動設(shè)置,安裝
Router - 一直回車下去,直至項目創(chuàng)建完成
二. 清理項目里的一些東西
三. 簡單靜態(tài)路由
1. 先在 components 文件夾下創(chuàng)建 A-router.vue 和 B-router.vue兩個組件,組件內(nèi)容如下:
// A-router.vue
<template>
<div class="a-router">
這是路由頁面 A ,現(xiàn)在是最簡單的路由跳轉(zhuǎn)
</div>
</template>
- 在
router/index.js中定義路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Arouter from '../components/A-router.vue' // 1. 引入路由組件
import Brouter from '../components/B-router.vue'
Vue.use(VueRouter)
const routes = [
{ // 2. 定義路由
name: 'router-a', //定義路由的名字
path: '/a', // 指定路由路徑
component: Arouter // 要跳轉(zhuǎn)的組件
},
{
name: 'router-b',
path: '/b',
component: Brouter
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
- 在
main.js中注入路由
import Vue from 'vue'
import App from './App.vue'
import router from './router' //導(dǎo)入 router,一般都是默認(rèn)導(dǎo)好的
Vue.config.productionTip = false
new Vue({
router, // 通過 router 配置參數(shù)注入路由,從而讓整個應(yīng)用都有路由功能,一般也是不需要自己配置的
render: h => h(App)
}).$mount('#app')
- 在
App.vue中使用路由
<template>
<div id="app">
<h1>Vue Router</h1>
<!-- 1. 使用 router-link 組件來導(dǎo)航. -->
<!-- 通過傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認(rèn)會被渲染成一個 `<a>` 標(biāo)簽 -->
<router-link to="/a">Router-A</router-link>
<router-link to="/b">Router-B</router-link>
<hr>
<!-- 2. 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
</template>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#app {
padding: 30px;
}
#app a {
font-weight: bold;
color: #2c3e50;
padding: 10px;
}
#app a.router-link-exact-active {
color: #42b983;
}
</style>
此時,一個簡單的靜態(tài)路由就配置好了
動態(tài)路由匹配
// router/index.js 文件
添加路由C
{
name: 'router-c',
path:'/c/:id', //動態(tài)路徑參數(shù) 以冒號開頭,當(dāng)匹配到一個路由時,參數(shù)值會被設(shè)置到 this.$route.params,可以在每個組件內(nèi)使用
component:Crouter
}
// App.vue 文件
<router-link :to="{name:'router-c',params:{id:123}}">Router-C</router-link>
// C-router.vue
<div>$route.params.id-->{{$route.params.id}}</div>