路由的基本配置
path
component
name
路由指定命名,设置后可⽤params传参及使⽤name进⾏路由跳转
路由的跳转
router-link标签跳转
编程式导航
path和query搭配
params和name搭配
动态路由
:什么是动态路由?
组件是同⼀个,只是通过不同的url参数渲染不同的数据
路径参数"使⽤冒号" : 标记
// route可以是对象,或者是字符串
// 对象的时候可通过路由的path或者name进⾏跳转
// 字符串的话只能是路由的path
this.$router.push(route)
// 路由传递参数, query和path配合, params和name配合
query: this.$router.push({path: '/', query: {id: 2}})
params: this.$router.push({name: 'home', params: {id: 2}})
{
path: '/home/:id',
component: home
} 在path⾥显式声明后,通过params传参后,参数不丢失同时参数被设置成必传参数
toHome: function () {
this.$router.push({path:'/home',query:{name:'Jack'}})//传递参数
this.$router.push({params: {id: 3},name: 'home'})
嵌套式路由:比如页面头部尾部不换,中间换掉,组件中嵌套不同组件
// 在需要嵌套的路由中补充children字段
{
path: '/home/:id',
component: home,
children: []
}
导航守卫:
// to, from是路由对象,我们在路由⾥定义的参数都可以在这⾥取到,例如to.path或
from.name
router.beforeEach((to, from, next) => {
// ...
next()
})
如main.js中
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
router.beforeEach(
(to,from,next)=>{ //导航守卫
console.log(to.path)
next() //必须调用next方法后
}
)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
路由懒加载:
提⾼⻚⾯加载速度
避免进⼊项⽬后加载全部组件
在路由中的component中设置函数,⽤import⽅式进⾏使⽤
component: () => import('./views/Home.vue'),
import vue from "vue"
import router from "vue-router"
Vue.use(Router)
export default new Router({
routes: [
{
// path: '/home/:id',动态路由的传递参数
path: '/home/:id',//意思就是必须传id才能进入页面
name:'home',//定义该属性
component: () => import('./views/Home.vue'),//路由懒加载
children: [{
path: '/child',//定义这个路径
component: () => import('./views/Child.vue')
}]//要定义的组件,在HOME里就显示出组件了,注意是列表表示。嵌套路由?
}]
})
<template>
<div id="app">
this is app
<!-- <router-view />-->
<button @click="passMsg">传你</button>
<m-parent :msg="c"></m-parent>
<router-link>to ="/home" > home</router-link> //router-link跳转
<button @click="toHome">home</button> //编程式跳转
<router-view></router-view>
hi Iam there// router
</div>
</template>
<style></style>
<script>
import bus from './util/bus'
import MParent from './views/Parent'
export default {
data(){
return{
a:'msga',
b:'msga',
c:'msga',
}
},
components: {
MParent
},
methods:{
passMsg(){
bus.$emit('msg','i am from app')
},
toHome: function () {
// this.$router.push({path:'/home',query:{name:'Jack'}})传递参数
this.$router.push({params: {id: 3},name: 'home'})//push跳转
}
}
}
</script>
<template>
<div>
<div>
this is home
<h1>{{$route.params.id}}</h1>//之前传入的id(:id)
<router-view></router-view> //在哪里显示
</div>
</div>
</template>
<script>
// // @ is an alias to /src
// import HelloWorld from "@/components/HelloWorld.vue"
export default {
name: "Home",
components: {}
}
</script>
<style lang="scss" scoped>
</style>