一、路由
不需要每次更新頁(yè)面都重新取一次數(shù)據(jù),只需要取一次。
- 配置
出現(xiàn)錯(cuò)誤:將vue-router文件放在了js主文件的后面。調(diào)整過(guò)來(lái)錯(cuò)誤消失。
var routes = [
{
path:'/',
component: {
template:`
<div>
<h1>首頁(yè)</h1>
</div>
`,
},
},
{
path:'/about',
component: {
template:
`
<div>
<h1>關(guān)于我們</h1>
</div>
`,
},
},
];
var router = new VueRouter({
routes: routes,
});
new Vue({
el:'#seg1',
router:router,
});
- 傳參
{
path: '/user/:name',
component: {
template: `
<div>
<h1>我叫{{$route.params.name}}</h1>
// 通過(guò)url里面的一部分
<h1>我{{$route.query.age}}歲了</h1>
// 通過(guò)URL中加?age=年齡來(lái)傳參
</div>
`,
},
},
- 子路由
加載路由頁(yè)面的里面,component后面
{
path: '/user/:name',
component: {
template: `
<div>
<h1>我叫{{$route.params.name}}</h1>
<h1>我{{$route.query.age}}歲了</h1>
<router-link :to="'/user/' + $route.params.name +'/more'">更多信息</router-link>
<router-view></router-view>
</div>
`,
},
// <router-link to="more" append>更多信息</router-link>
// <router-link :to="'/user' + $route.params.name +'/more'">更多信息</router-link>
children:[
{
path: 'more',
component: {
template: `
<div>
用戶{{$route.params.name}}的詳細(xì)信息
傻傻傻
</div>
`,
},
},
],
},
- 手動(dòng)訪問(wèn)和傳參
一個(gè)點(diǎn)擊方法:
methods:{
get:function () {
setTimeout(function(){
this.router.push('/about');
setTimeout(function(){
this.router.push({name:'user',params:{name:'王花花'}});
},2000)
},2000)
}
}
- 命名視圖
頁(yè)面中的命名視圖最好只有兩個(gè),多了不好維護(hù)
<div>
<router-link to="/">首頁(yè)</router-link>
<router-link to="/user">用戶管理</router-link>
</div>
<div>
<router-view name="sidebar"></router-view>
<router-view name="content"></router-view>
</div>
{
path: '/user',
components: {
sidebar:{
template: `
<div>
<ul>
<li>用戶列表</li>
<li>權(quán)限管理</li>
</ul>
</div>
`,
},
content:{
template: `
<div>
用戶管理
</div>
`,
}
},
},
- 導(dǎo)航鉤子
檢查路由:
beforeEach:將登陸值設(shè)置為false,
如果已經(jīng)登陸,就正常跳轉(zhuǎn),如果沒(méi)有就跳轉(zhuǎn)到登陸頁(yè)。
afterEach:判斷一些信息
router.beforeEach(function (to,from,next) {
var logged = false;
if(!logged && to.path == '/post')
next('/login');
else
next();
});
router.afterEach(function (to,from) {
//判斷前一頁(yè)下一頁(yè)
});
```-