除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。在 Vue 实例内部,可以通过 $router 访问路由实例。因此可以调用 this.$router.push。
Router实例方法
1. router.push(参数) 向 history 栈添加一个新的记录
、 router.push('home')
router.push({ path: 'home' })
router.push({ name: 'user', params: { userId: '123' }})
router.push({ path: 'register', query: { plan: 'private' }})
如果参数对象中是path, params 不生效,只能通过query来传递
2. router.replace(参数) 与push非常类似,不同的是不在history中加入新的记录,而是替换当前的history记录
3. router.go(num) 这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
</head>
<body>
<div id="app">
<!-- 4.路由的使用 -->
<router-link to="/a">去A路由</router-link>
<router-link to="/b">去B路由</router-link>
<button @click='$router.push("/a")'>去A1路由</button>
<button @click='$router.push("a")'>去A2路由</button>
<button @click='toPath'>去A3路由</button>
<!-- 为组件加载提供容器/窗口 -->
<!-- 实现了组件之间的动态加载 -->
<!-- 显示路由 -->
<router-view></router-view>
</div>
<script>
// 1.注册组件
let myA = {
data() {
return {
id: null,
username: null,
}
},
template: `
<div>
A组件--{{id}}--{{username}}
</div>
`,
created() {
console.log(this.$route);
}
}
let myB = {
template: `
<div>
B组件
</div>
`
}
// 创建路由对象数组
let routes = [{
path: '/a',
component: myA,
name: 'myA'
}, {
path: '/b',
component: myB
}]
//创建路由器对象实例
let router = new VueRouter({
routes,
mode: 'history',
})
new Vue({
el: '#app',
//3.局部注册路由器对象
router,
components: {
'my-a': myA,
'my-b': myB
},
data: {},
methods: {
toPath() {
//历史记录路由
// this.$router.go(1)
this.$router.replace('/a')
// this.$router.push({
// //有效
// path: '/a?id:1',
// name: 'myA'
// // query: {
// // id: 1
// // },
// // //无效
// // params: {
// // name: 'terry'
// // }
// })
}
},
})
</script>
</body>
</html>