vue-router和vuex是官方提供的Vue插件,主要解决路由和状态管理两个问题
vue-router
基本概念
解决什么问题?vue-router解决了路由与组件的对应关系
- vue-router的基本使用方法
npm i -S vue-router
cnpm i -S vue-router
- 使用vue-router插件
import Route from 'vue-router'
import A from './components/A.vue'
import B from './components/B.vue'
Vue.use(Route)
注:下述代码是用于关闭调试窗口重不重要描述
Vue.config.productionTip = false
- 初始化vue-router对象
const routes = [
{ path: '/a', component: A },
{ path: '/b', component: B },
{ path: '/hello-world', component: HelloWorld }
]
const router = new Route({
routes
})
- 实例化Vue对象,传入router参数
new Vue({
router,
render: h => h(App)
})
- .使用router-view和router-link
router-view和router-link是vue-router官方提供的两个组件,router-view会替换为路由对应的组件,router-link相当于a标签,点击后会加载to属性中路由对应的组件
<div>
<div>
<router-link to="/a">a</router-link>
</div>
<div>
<router-link to="/b">b</router-link>
</div>
<div>
<router-link to="/hello-world">hello-world</router-link>
</div>
</div>
<router-view />
路由嵌套
实现/a/aa路由,并且/aa对应的组件嵌套在/a之下,这时我们需要修改路由的配置文件:
const routes = [{
path: '/a',
component: A,
redirect: '/a/aa',
children: [
{
path: '/a/aa',
component: AA,
}]
}]
并修改A组件的内容:
<template>
<div>
<div>a</div>
<router-view />
</div>
</template>
由于A组件是父级路由,所以也需要添加router-view组件,动态匹配子路由
重定向
将一个路由重定向到另一个路由,实际开发过程中非常实用,修改配置文件即可:
const routes = [{
path: '/a',
component: A,
redirect: '/a/aa',
children: [{
path: '/a/aa',
component: AA,
}]
}]
动态路由
为了支持restful形式路由以及更复杂的场景时,我们可以使用动态路由,定义路由时,在路由前加上冒号即可,我们先添加AA2组件,动态路由部分通过this.$route.params进行接收:
<template>
<div>
aa2
<div>{{id}}</div>
</div>
</template>
<script>
export default {
data() {
return {
id: null
}
},
created() {
this.id = this.$route.params.id
}
}
</script>
修改路由配置后生效:
const routes = [
{
path: '/a',
component: A,
redirect: '/a/aa',
children: [
{
path: '/a/aa',
component: AA,
},
{
path: '/a/:id',
component: AA2,
},
]
}
]
动态路由的优先级低于普通路由,所以我们访问/a/aa时会匹配到AA组件,而输入其他路由时会匹配到AA2组件
路由参数
参数传递是我们开发过程中必不可少的步骤,vue-router支持参数传递,通过this.$route.query进行接收,我们修改AA组件进行测试。
<template>
<div>
aa
<div>{{message}}</div>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
created() {
this.message = this.$route.query.message || ''
}
}
</script>
编程式路由
有很多时候我们需要手动操作路由的跳转,这时我们需要使用this.$router,以下是一些常用的操作:
- 路由跳转
this.$router.push('/a/aa')
- 带参数路由跳转
this.$router.push({
path: '/a/aa',
query: {
message: 'hello'
}
})
- 不向history插入记录
this.$router.replace('/a/123')
- 回退
this.$router.go(-1)