创建路由的基本流程:
- 在head头文件中书写如下代码:
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-router/dist/vue-router.js"></script>
- 装载容器里写路由菜单,路由出口
<div id="app">
<div>
<!-- 路由菜单 -->
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>
</div>
<!-- 路由 出口 -->
<router-view></router-view>
</div>
- 在script中定义组件,定义路由项,创建路由实例,创建vue实例
- 路由项:数组的形式
path:路径
component:组件
- 将路由项传递给路由实例
- 将路由实例传递给vue实例
<script>
//定义组件
const Home = {
template:'<p>主页</p>',
}
const News = {
template:'<p>新闻</p>',
}
//定义路由项 数组的形式
const routes=[
{path:'/home',component:Home},
{path:'/news',component:News}
]
//创建路由实例
const router = new VueRouter({
routes
});
let vm = new Vue({
el:'#app',
router
})
</script>
路由传参:
<template id="Home">
<div>
<p>主页</p>
<router-link to="/home/register" >注册</router-link>
<router-link to="/home/login" >登录</router-link>
<div>
<router-view></router-view>
</div>
</div>
</template>
<template id="News">
<div>
<p>新闻页</p>
<div>
<router-link to="/newsDetail/1" >新闻1</router-link>
<router-link to="/newsDetail/2" >新闻2</router-link>
<router-link to="/newsDetail/3" >新闻3</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
</template>
===============================================================
<template id="NewsDetail">
<div>
<!-- $route.params.id获取路由上的参数 -->
{{$route.params.id}}
</div>
===============================================================
const NewsDetail = {
template:'#NewsDetail'
}
路由的编程
- replace实现路由跳转:根据路由项的name进行跳转
- push 方法根据路由项的path进行跳转
- push 方法根据路由项的query进行跳转
<body>
<div id="app">
<div>
<button type="button" @click="fun1()">跳转1</button>
</div>
<div>
<button type="button" @click="fun2()">跳转2</button>
</div>
<div>
<button type="button" @click="fun3()">跳转3</button>
</div>
<router-view></router-view>
</div>
<script>
const router = new VueRouter({
routes:[
{
path:'/index/:id',//路由的路径
name:'index',//路由的名称,可选属性,定义后可以用于实现跳转
component:{//组件
template:'<div>{{$route.params.id}}//组件模板</div>'
}
},
{
path:'/test/:id',//通过路由传参
name:'text',
component:{
template:'<div>{{$route.params.id}}</div>'
}
},
{
path:'/go',
name:'go',
component:{
template:'<div>{{$route.query.uid}}</div>'
}
},
]
});
let vm = new Vue({
el:'#app',
router,
methods:{
fun1(){
//replace实现路由跳转:根据路由项的name进行跳转
this.$router.replace({name:'index',params:{id:Math.random()}});
},
fun2(){
//push 方法根据路由项的path进行跳转
this.$router.push(`/text/${Math.random()}`);
},
fun3(){
//push 方法根据路由项的query进行跳转
this.$router.push({path:'/go',query:{uid:110}})
}
},
});
</script>
</body>