1 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
2 创建路由new VueRouter(),接受的参数是一个对象
3 在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性
4 path属性是url的地址,component属性就是显示的组件(传组件的对象)
5 创建的路由需要和vue实例关联一下
6 路由到的组件显示在哪个位置
<router-view name="play"></router-view>
<router-view name="detail"></router-view>
<router-link :to="{path:'/detail',query:{course:103} }">跳转详情1</router-link>
<router-link :to="{name:'my',params:{userid:10,age:20} }">跳转我的</router-link>
<router-view></router-view>
</div>
<template id="index">
<div>
index
<a href="#/detail">通过a跳转</a>
<!-- 声明式跳转 -->
<router-link to="/detail?courseid=103&age=18">跳转详情</router-link>
<router-link :to="{path:'/detail' }">跳转详情1</router-link>
<router-link :to="{path:'/detail',query:{course:103} }">跳转详情1</router-link>
<router-link :to="{name:'my',params:{userid:10,age:20} }">跳转我的</router-link>
<!-- 错误的写法 -->
<!-- <router-link :to="{name:'my' }">跳转我的1</router-link> -->
<!-- 函数式跳转 -->
<button @click="todetail">跳转详情</button>
<button @click="tomine">跳转我的</button>
</div>
</template>
<template id="detail">
<div>
detail
<router-view></router-view>
</div>
</template>
<template id="mine">
<div>
mine
</div>
</template>
<template id="play">
<div>
play
</div>
</template>
<script>
let play = {
template: '#play'
}
let mine = {
template: '#mine',
created() {
console.log(this);
console.log(this.$route.params.userid);
}
}
let index = {
template: '#index',
methods: {
todetail() {
console.log(this);
this.$router.push({
path: "/detail",
query: {
course: 104
}
})
},
tomine() {
this.$router.push({
name: 'my',
params: {
userid: 1111
}
})
}
}
}
let detail = {
template: '#detail',
created() {
console.log(this.$route.query.course);
}
}
// 2、创建路由对象:
const router = new VueRouter({
// 3、创建映射关系
routes: [
// 路由重定向
{
path: '/',
redirect: '/index'
},
{
path: '/index',
// component: index,
components: {
default: index,
play,
detail
}
},
{
path: '/detail',
component: detail,
// 路由嵌套
children: [
{
path: 'play',
component: play,
// children: [
// {
// path: 'url',
// component: 组件
// }
// ]
}
]
},
{
path: '/mine/:userid',
component: mine,
name: 'my'
},
],
// 自定义路由高亮
linkActiveClass: 'active'
})
const vm = new Vue({
// 4、将路由挂载在vue实例上
// router: router,
router,
el: '#app',
data: {
},
methods: {
}
})