vue-router的集成
1. 安装vue-router
$ npm install vue-router --save
2. 创建路由组件页面
<template>
<div class="one">
<text>
{{msg}}
</text>
</div>
</template>
<script>
export default {
data:()=>({
msg:'this is one'
})
}
</script>
代码结构如下
3. 集成
在src目录创建router目录,用于存放路由相关信息,然后在router中新建index.js。进行路由的配置以及与Router的集成,以下是src/router/index.js的代码
import Router from 'vue-router'
//组件导入
import ViewOne from '../pages/one/index.vue'
import ViewTwo from '../pages/two/index.vue'
import ViewThree from '../pages/three/index.vue'
//将Vue-router继承到Vue中
Vue.use(Router);
//提供默认对外接口
export default new Router({
// mode: 'abstract',
routes: [
{ path: '/one', component: ViewOne },
{ path: '/two', component: ViewTwo },
{ path: '/three', component: ViewThree }
]
});
然后在entry.js中导入router的配置
import App from './App.vue'
//引入路由配置
import router from './router'
new Vue(Vue.util.extend({
el:'#root',
//将vue集成到vue中
router,
},App))
4. 路由编程
在App.vue中提供<router-view>指令,用于显示路由信息
<template>
<div class='container'>
<!-- 标题 -->
<div class="panel titlePanel">
<text class='title'>{{msg}}</text>
</div>
<!-- 导航区 -->
<div class="panel">
<text class='link' @click='linkTo("/one")'>one</text>
<text class='link' @click='linkTo("/two")'>two</text>
<text class='link' @click='linkTo("/three")'>three</text>
</div>
<!-- 视图区 -->
<router-view></router-view>
</div>
</template>
<script>
export default{
data(){
return {
msg:'你好,weex'
}
},
methods:{
linkTo(path){
//点击后改变路由
this.$router.push(path);
}
}
}
</script>
<style>
.container {
background-color:#f4f4f4;
}
.panel {
flex-direction: row;
height: 100px;
border-bottom-width: 1px;
justify-content: space-between;
}
.titlePanel {
justify-content: center;
background-color: #ededed;
}
.title {
height: 100px;
line-height: 100px;
}
.link{
line-height: 100px;
text-align: center;
flex: 1
}
</style>
运行效果