笔记附在最后.
npm install vue-router --save
安装VUE路由,--save是因为在上线后还要使用
使用脚手架导入的话就不用安装了
这是自动创建的标准代码(来自src/router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
删除helloworld和app中相关样式后,正式拿到了一个空白界面
router-link--->用于跳转vue组件,vue已经注册了的全局组件
router-view--->用于看vue组件在什么地方渲染(相当于占位符)
mode:'history',改变url模式
嵌套路由,在子组件中添加
<router-link to="/home/mess">message</router-link>
<router-view></router-view>
在index.js(路由)中添加children路径
!!!子组件出现公共style会污染其他组件???(详情请见h1)
在已经打开/user/Eille后再次点击user按钮会报错 Avoided redundant navigation to current location: "/user/Eille"
导航守卫,用于监听跳转的过程,应用广泛(改变界面标题)
creat,在组件创造好以后执行
meta:{
title:'Home'
}
router.beforeEach((to,from,next)=>{
//从from跳转到to
document.title=to.meta.title;
next();//调用beforeEach以后必须实现next方法,不然所有跳转无法实现
});
以在Vue中写的方法为准(实质上是方法andcomputed在路由之后?)
额外注意,(在添加改变标题,面对有多个子组件,显示undefined时候有2种方法)
1---给每个子组件加meta,之后就能显示详细title(如->Home_NEWS),代码如下
children:[
{
path:'news',//子路由不用加/,会自动拼接
component:news,
meta:{
title:'Home_NEWS'
}
},
{
path:'mess',//子路由不用加/,会自动拼接
component:()=>import('../components/home_mess'),
meta:{
title:'Home_MESS'
}
},
{
path:'',
redirect:'news',
},
],
meta:{
title:'Home'
}
},
router.beforeEach((to,from,next)=>{
//从from跳转到to
document.title=to.meta.title;
next();//调用beforeEach以后必须实现next方法,不然所有跳转无法实现
});
--------------------------------------
2使用macth匹配,无需在children添加,但是相应的只能显示Home,代码如下
router.beforeEach((to,from,next)=>{
//从from跳转到to
document.title=to.matched[0].meta.title;//这里是重点
next();//调用beforeEach以后必须实现next方法,不然所有跳转无法实现
});
meta为元数据(用于描述数据的数据)
//前置钩子(前置守卫)
router.beforeEach((to,from,next)=>{
后置钩子 -> aftereach不需要调用next函数
<keep-alive exclude="profile">
<!-- exclude,在里面的每次都会被销毁,传入name属性 -->
<!-- 用于保持组件不被销毁,保留在缓存中,(显示的地方就是不销毁的数量) -->
<router-view></router-view>
</keep-alive>
require ('./assets/css/base.css');
在js中引入css
@import "./assets/css/base.css";
在js中引入css
在build/webpack.base.conf.js里面,有以下函数(27行左右起~),你也可以自己创造相关的
resolve: {
extensions: ['.js', '.vue', '.json'],//显示可以省略的后缀
alias: {//在这里给文件夹起别名!!
'@': resolve('src'),//给src(资源文件起了别名叫做@)
<请注意,像这样这种在html代码里面导入时候要在前面加~>
}
},