vue2.0路由变化1

路由的步骤

1.定义组件

var Home={
template:'<h3>我是主页</h3>'
};
var News={
template:'<h3>我是新闻</h3>'
};

2.配置路由

const routes=[
{path:'/home', componet:Home},
{path:'/news', componet:News},
];

3.生成路由实例

const router=new VueRouter({
routes
});

(代码量不大时二三步可以合并)

4.挂到vue上

new Vue({
router,
el:'#box'
});

vue2.0的改变

1.嵌套使用方式的改变

const routes=[
{path:'/home', component:Home},
{
path:'/user',
component:User,
children:[ //核心
{path:'username',//path路径不要再以"/"开头,不然会认为从根路径开始
component:UserDetail}
]
},
];
  1. 跳转方式

废弃了a便签,引入了router-link

<router-link to="/user/hhh/age/10">hhh</router-link></li>

router-view还是不变

3. 获取数据

<li><router-link to="/user/hhh/age/10">hhh</router-link></li>
...
var UserDetail={
template:'<div>{{$route.params}}</div>'
};
...
const routes=[
{path:'/home', component:Home},
{
path:'/user',
component:User,
children:[{
path:':username/age/:age',
component:UserDetail
}]
},
{path:'*', redirect:'/home'}
];
  1. 路由实例方法:
router.push({path:'home'});

直接添加一个路由,表现切换路由,本质往历史记录里面添加一个

router.replace({path:'news'})

替换路由,不会往历史记录里面添加

全部代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>智能社——http://www.zhinengshe.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<style> </style>
<script src="vue.js"></script>
<script src="bower_components/vue-router/dist/vue-router.min.js"></script>
</head>
<body>
<div id="box">
<div>
<input type="button" value="添加一个路由" @click="push">
<input type="button" value="替换一个路由" @click="replace">
<router-link to="/home">主页</router-link>
<router-link to="/user">用户</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
<script>
var Home = {
template:'<h3>我是主页</h3>'
};
var News = {
template:'<h3>我是用户</h3>'
};
var User = {
template:`
<div>
<h3>我是用户信息</h3>
<div>
<li><router-link to="/user/hhh/age/10">hhh</router-link></li>
<li><router-link to="/user/ggg/age/20">ggg</router-link></li>
<li><router-link to="/user/ttt/age/30">ttt</router-link></li>
</div>
<div>
<router-view></router-view>
</div>
</div>
`
};
var UserDetail={
template:'<div>{{$route.params}}</div>'
};
const routes=[
{path:'/home', component:Home},
{
path:'/user',
component:User,
children:[{
path:':username/age/:age',
component:UserDetail
}]
},
{path:'*', redirect:'/home'}
]; //生成路由实例
const router=new VueRouter({
routes
});
new Vue({
router,
methods:{
push:function() {
router.push({path:'/home'});
},
replace:function(){
router.replace({path:'user'});
}
}
}).$mount('#box')
</script>
</body>
</html>
上一篇:Vue2.0的变化 ,组件模板,生命周期,循环,自定义键盘指令,过滤器


下一篇:Yii框架tips