一、路由
(1)引入vue、vue-router组件
(2)引入项目的其它组件
(3)全局注册router组件
(4)配置路由表
* 默认加载
* 嵌套路由
* 嵌套路由的默认加载
* 路由的元数据
/*
路由模块
*/
import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入路由组件文件夹下的组件
// import Msite from '../pages/Msite/Msite.vue'
// import Search from '../pages/Search/Search.vue'
// import Order from '../pages/Order/Order.vue'
// import Profile from '../pages/Profile/Profile.vue'
//引入登录路由
import Login from '../pages/Login/Login'
import Shop from '../pages/Shop/Shop.vue'
import ShopGoods from '../pages/Shop/ShopGoods/ShopGoods.vue'
import ShopRatings from '../pages/Shop/ShopRatings/ShopRatings.vue'
import ShopInfo from '../pages/Shop/ShopInfo/ShopInfo.vue'
// 路由组件懒加载,在发起路由请求时才去后台加载组件
const Msite = () => import('../pages/Msite/Msite.vue')
const Search = () => import('../pages/Search/Search.vue')
const Order = () => import('../pages/Order/Order.vue')
const Profile = () => import('../pages/Profile/Profile.vue')
// 全局注册Vue-router组件
Vue.use(VueRouter)
// 配置路由表并导出
export default new VueRouter({
// 去掉地址中的哈希#
mode: 'history',
routes: [
/* 默认加载/msite对应的路由组件 */
{
path: '/',
redirect: '/msite'
},
{
path: '/msite',
component: Msite,
meta: {
showFooter: true
}
},
{
path: '/search',
component: Search,
meta: {
showFooter: true
}
},
{
path: '/order',
component: Order,
meta: {
showFooter: true
}
},
{
path: '/profile',
component: Profile,
meta: {
showFooter: true
}
},
/* 配置登录*/
{
path: '/Login',
component: Login
},
{
path: '/shop',
component: Shop,
/* 嵌套路由 */
children: [{
path: 'goods',
component: ShopGoods
},
{
path: 'ratings',
component: ShopRatings
},
{
path: 'info',
component: ShopInfo
},
/*默认加载goods对应的组件*/
{
path: '',
redirect: 'goods'
}]
}
]
})
【注意】写完脚本文件之后,记得在入口文件main.js里面引入,并挂在到vue实例中!
// 引入路由 其实就是router文件夹下的index.js配置好的路由表
import router from './router'
new Vue({
el: '#app',
components: { App },
// 为根组件加入路由
router, //使用vue-router
store //使用vuex
})
二、路由组件传参(非常重要要!!!)
方式一
传参
在相应的路由内接参:
【注意】这种传参的方式,路由的规则不会变!
【方式一拓展】
<router-link :to="{path:'/shop', query:{id:'12',name:'pzz'}}" tag="li">
【注意】 to是属性绑定的! 而且router-link默认是a链接,可以通过tag属性指定router-link变成指定标签!
方式二
在相应的路由接收参数:
【注意】方式二路由规则都变了!
方式二拓展:
<router-link :to="{path:'/shop', params:{id:'12',name:'pzz'}}" tag="li">
【注意】 to是属性绑定的! 而且router-link默认是a链接,可以通过tag属性指定router-link变成指定标签!
3. $route 当前路由对象
this.$route.meta 获取路由组件元信息
this.$route.path 获取请求路径
this.$route.query 获取参数
this.$route.params 获取参数
4. $router路由器对象
this.$router.replace(path) 同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。
this.$router.push(path) 跳转到不同的url,但这个方法回向history栈添加一个记录,点击后退会返回到上一个页面。
this.$router.back() 返回上一级路由
5. keep-alive 在浏览器中缓存从后台获取的数据!
<keep-alive>
<router-view/>
</keep-alive>