通过Vue路由实现Tab栏切换案例,要求为:创建3个子路由,分别是“待付款”、“待发货”、“待收货”,在每个子路由页面单独写出相应的内容,页面效果如下。
下面开始编辑。
首先在头部引用本次实例要用的Vue、Vue-router、Vuex。
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex/dist/vuex.js"></script>
创建Vuex和Vue实例
var vm = new Vue({
el: '#app',
router: router
})
var store = new Vuex.Store({
state: {
status: '待付款'
}
})
创建路由实力与其组建
<template id="daifukuan">
<div>
<p>商品的状态为:<span style="color: crimson;">{{this.$store.state.status}}</span></p>
<button @click="changeStatus" v-if="this.$store.state.status == '待付款'">付款</button>
</div>
</template>
<template id="daifahuo">
<div>
<p>商品的状态为:<span style="color: crimson;">{{this.$store.state.status}}</span></p>
<button @click="changeStatus" v-if="this.$store.state.status == '已付款'">发货</button>
</div>
</template>
<template id="daishouhuo">
<div>
<p>商品的状态为:<span style="color: crimson;">{{this.$store.state.status}}</span></p>
<button @click="changeStatus" v-if="this.$store.state.status == '已发货'">收货</button>
</div>
</template>
//创建组件
var daifukuan = {
template: '#daifukuan',
store: store,
methods: {
changeStatus() {
this.$store.state.status = '已付款'
}
}
}
var daifahuo = {
template: '#daifahuo',
store: store,
methods: {
changeStatus() {
this.$store.state.status = '已发货'
}
}
}
var daishouhuo = {
template: '#daishouhuo',
store: store,
methods: {
changeStatus() {
this.$store.state.status = '已收货'
}
}
}
//创建路由实例
var router = new VueRouter({
routes: [{
path: '/daifukuan',
component: daifukuan
},
{
path: '/daifahuo',
component: daifahuo
},
{
path: '/daishouhuo',
component: daishouhuo
},
]
})
编写HTML界面
<div id="app">
<div style="display: flex;">
<router-link to="/daifukuan" tag="div" class="title">
待付款
</router-link>
<router-link to="/daifahuo" tag="div" class="title">
待发货
</router-link>
<router-link to="/daishouhuo" tag="div" class="title">
待收货
</router-link>
</div>
<router-view class="content"></router-view>
</div>
加入CSS样式
通过.router-link-active设置背景颜色设置被选中路由页面标题高亮,简化了繁琐的js设置高亮。
<style>
.title {
width: 100px;
height: 50px;
border: 1px solid black;
text-align: center;
line-height: 50px;
}
.content {
width: 304px;
height: 200px;
border: 1px solid black;
text-align: center;
line-height: 100px;
}
.router-link-active {
background-color: burlywood;
}
</style>