路由管理
路由的安装
1. cnpm install vue-router --save -dev
路由的挂载
路由的挂载在mian.js 中进行引入
import vueRouter from 'vue-router'
//路由入口页面
import home from './component/home'
import my from './component/my'
//挂载到vue
Vue.use(vueRouter)
配置路由
在main.js中引入路由后接着进行路由的配置
let Router = new vueRouter({
routes:[
{
path:"/",//引入组件的路径
component:"home"//引入的组件名称
},
{
//第一种是动态传值的方式,需要写入参数
path:"/my",//引入组件的路径
component:"my/:id"//引入的组件名称
//第二种是get传值方式不需要写入参数
path:"/my",
component:my,
},
{
path:"*",
redirect:"/"
//表示重定向,即如果没有这个路由,则跳转到"/"重定向页面
}
]
})
路由的入口和出口
App.vue中引入路径入口和路径出口对应的组件
//路由入口
import footer from './component/footer'
//路由出口
import content from './component/content'
设置路由入口,并给路由入口设置子组件路径
//路由入口使用<router-link></router-link>组件
//:to="/home"表示路由入口样式组件,下边会介绍
<router-link :to="/home">
</router-link>
在content组件中使用router-view组件设置路由的出口
<router-view></router-view>
传值-给home 传值
//1.使用动态传值,可使用ES6模版语法
<router-link :to="`/my/1000`" >
</router-link>
//在my里获取动态路由传值
mounted(){
console.log(this.$routes.params);
}
//2,使用get传值
<router-link :to="{path:'/my',query:{'id':100}}">我的
</router-link>
//路由的get传值获取
mounted(){
console.log(this.$route.query);
}
//3,设置子组件的路由出口
//新建一个组件并设置以下代码
<div id="continfo">
<router-view></router-view>
</div>
路由的编程式导航
在my组件中操作
<div id="myinfo">
我是my详细的具体内容
<!-- 拿代码操作路由跳转-- 路由导航 -->
<button @click=gorouter()>跳转</button>
</div>
export default{
name:'myinfo',
methods:{
//1,第一种,push方法里边直接写路由的路径
this.$router.push("/");
//2,第二种push方法里面写对象
this.$router.push({path:"/"})
//3,第三种是跳转的时候携带参数。get传值方式
this.$router.push({
path:'/',
query:{
id:100
}
});
//4,编程里的动态路由传值
this.$router.push({
path:'/my/100'//这种在跳转的时候需要保证
//和路由配置上的参数一致要不跳转不了
//那么my的路由设置必须是'/my/:id'即参数要一致
})
}
路由的嵌套
主要针对的是子父路由之间的关系
首先,创建cart组件,作为my组件的子组件
<div id="cartinfo">
我是my的子组件
</div>
在mian.js 中引入cart组件
impor cart from './component/cart'
在父路由下设置子路由
{
path:"/my",
component:my,
children:[
{
//子路由可能有若干个,这里只设置一个
path:"/my/cart",
component:cart
}
]
}
在my中设置路由的入口和出口
<router-link :to="/my/cart"></router-link>
<router-view></router-view>