◆ 頁面導航的兩種方式:
- 聲明式導航:通過點擊鏈接的方式實現的導航
- 編程式導航:調用js的api方法實現導航
◆ Vue-Router中常見的導航方式:
- this.$router.push(“hash地址”);
- this.$router.push("/login");
- this.$router.push({ name:‘user’ , params: {id:123} });
- this.$router.push({ path:"/login" });
- this.$router.push({ path:"/login",query:{username:“jack”} });
- this.$router.go( n );//n爲數字,參考history.go
- this.$router.go( -1 );
◆ 示例:
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 導入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 實例所控制的區域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link :to="{ name: 'user', params: {id: 3} }">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由佔位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id', 'uname', 'age'],
template: `<div>
<h1>User 組件 -- 用戶id爲: {{id}} -- 姓名爲:{{uname}} -- 年齡爲:{{age}}</h1>
<button @click="goRegister">跳轉到註冊頁面</button>
</div>`,
methods: {
goRegister() {
this.$router.push('/register')
}
},
}
const Register = {
template: `<div>
<h1>Register 組件</h1>
<button @click="goBack">後退</button>
</div>`,
methods: {
goBack() {
this.$router.go(-1)
}
}
}
// 創建路由實例對象
const router = new VueRouter({
// 所有的路由規則
routes: [
{ path: '/', redirect: '/user' },
{
// 命名路由
name: 'user',
path: '/user/:id',
component: User,
props: route => ({ uname: 'zs', age: 20, id: route.params.id })
},
{ path: '/register', component: Register }
]
})
// 創建 vm 實例對象
const vm = new Vue({
// 指定控制的區域
el: '#app',
data: {},
// 掛載路由實例對象
// router: router
router
})
</script>
</body>