特意整理了一下 vue-router 的使用方法,可以整篇復制直接看效果,里面寫了很多注釋,幫助你看懂路由的使用方法
<!DOCTYPE html>
<html lang="en">
<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>
</head>
<body>
<div id="div1">
<div>
<!-- router-link的作用就是代替a標簽實現跳轉,好處是沒有刷新 -->
<router-link to="/home">首頁</router-link>
<router-link to="/about">關於我們頁</router-link>
<router-link to="/user/張三">張三</router-link>
<router-link to="/user/李四">李四</router-link>
<button @click="pushUser">手動添加訪問用戶</button>
</div>
<div>
<!-- 跳轉之后顯示的內容 -->
<router-view></router-view>
</div>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.0/vue.js"></script>
<script src="https://cdn.bootcss.com/vue-router/2.6.0/vue-router.js"></script>
<script> window.onload = function(){ // routesArr 的作用是配置好跳轉路徑和跳轉之后的內容
let routesArr = [ { path: '/home', component: { template:`<div>
<h1>這是首頁</h1>
</div>`
} },{ path: '/about', component: { template: `<div>
<p>這是關於我們頁</p>
</div>`
} },{ path: '/user/:name', // :name的作用是動態訪問一個地址,比如傳進來的是張三,就顯示張三的信息
name: 'user', // 這個name的作用是配合第95行添加屬性用的,二者必須一致
component: { template: `<div>
<!-- $route.params的作用是接收傳進來的名字,例如傳張三 name就是張三 -->
<p>我叫:{{ $route.params.name }}</p>
<!-- $route.query的作用是接收url上 ?age=18 這樣的參數 例如 router.html#/user/張三?age=18 -->
<p>我今年:{{ $route.query.age }} 歲了</p>
<div>
<!-- append是為了給下面的children子路由傳數據 -->
<router-link to="more" append> 更多信息 </router-link>
</div>
<!-- 這個router-view對應的就是children里的template -->
<router-view></router-view>
</div>`
}, children:[ { path: 'more', component: { template:` <div> 用戶:{{ $route.params.name }} 的詳細信息 abcd1234 </div>
` } } ] } ]; const vRouter = new VueRouter({ routes: routesArr // 這里要寫routes ,而不是routers,不然 <router-view> 沒數據
}) new Vue({ el: '#div1', router: vRouter, methods: { pushUser: function(){ // this.$router這個方法遍歷不到,但可以直接使用
this.$router.push({ name: 'user', // 和51行配合使用的,二者需一致
params: { name: '王五' } }); } } }) } </script>
</body>
</html>
