本節(jié)內(nèi)容
學(xué)會使用路由進(jìn)行組件切換
接上上節(jié)的內(nèi)容進(jìn)行講解路由的使用
- 第一步
創(chuàng)建一個父組件和兩個子組件
父組件foo.vue 的文件和子組件home.vue和me.vue
- 第二步 定義路由router.js 文件
// 定義路由
//第一步 導(dǎo)入路由模塊vue-router 和vue.js
import VueRouter from 'vue-router'
import Vue from 'vue'
// 第二步 導(dǎo)入組件
import home from './home.vue'
import me from './me.vue'
// 第三步 讓Vue 使用 vue-router 當(dāng)做自己的路由
Vue.use(VueRouter)
// 第四步 創(chuàng)建路由對象
export default new VueRouter({
// mode: 'abstract', // weex 中只能使用 abstract 類型 默認(rèn)可以不寫 系統(tǒng)會自動設(shè)置為abstract
// 定義路由
routes: [
{ path: '/home', component: home},
{ path: '/me', component: me}
// { path: '/article/:url(.*)?', component: ArticleView },
// { path: '/item/:id(\\d+)', component: CommentView },
// { path: '/user/:id', component: UserView },
// { path: '/', redirect: '/home' }
]
})
第三步 在入口的app.js文件中 創(chuàng)建根節(jié)點(diǎn)組件
// 第一步 導(dǎo)入根組件
import foo from './src/foo.vue'
// 第二步 導(dǎo)入路由文件
import router from './src/Router.js'
//第三步 給根組件一個id
foo.el = '#root'
//第四步給 給根組件設(shè)置路由
foo.router = router
// 第五步 創(chuàng)建Vue 對象
export default new Vue(foo);
// 第六步 指定一個路由入口
router.push('me')
第四步 我們看看我們的根組件的代碼
<template>
<div class="wrapper">
<div class="nav">
<text @click="jump('home')" :class="selectedPath=='home'?'nav-item-selected':'nav-item-normal'">主頁{{selectedTitleColor}}</text>
<text @click="jump('me')" :class="selectedPath=='me'?'nav-item-selected':'nav-item-normal'">我的</text>
</div>
<!-- 定義路由模板視圖 這個是用來加載組件的-->
<router-view class="template"></router-view>
</div>
</template>
<style>
.wrapper { align-items: center; margin-top: 40px; }
.nav{
display: flex;
flex-direction: row;
justify-content: space-around;
width:750px;
height: 88px;
}
.template{
position:absolute;
top: 128px;
bottom: 0px;
left: 0px;
right: 0px;
}
.nav-item-selected{
color:yellowgreen;
}
.nav-item-normal{
color:black;
}
</style>
<script>
export default {
data:{
selectedPath:'me'
},
methods: {
// 單擊按鈕跳轉(zhuǎn)到指定的路徑
jump: function (e) {
this.$router.push(e);
this.selectedPath = e;
}
}
}
</script>
第五步 home.vue 和me.vue 中的代碼
home.vue
<template>
<div class="home-container">
<text>主頁</text>
</div>
</template>
<script>
export default{
}
</script>
<style>
.home-container{
background-color:red;
width:750px;
font-size: 30px;
text-align: center;
}
</style>
me.vue
<template>
<div class="me-container">
<text>我的</text>
</div>
</template>
<script>
export default{
}
</script>
<style>
.container{
background-color: green;
width:750px;
font-size: 30px;
}
</style>
210ADF6F-3350-475E-BE90-200CD377829A.png
A6844CE7-BB6F-43F4-862E-EAFE71797D18.png
路由的作用是在單頁面內(nèi),進(jìn)行組件的切換!