vue-cli 3.0 通过 vuex.store 及 rout
2019-06-21 本文已影响0人
山上有桃子
最新使用vue-cli 3.0 重构公司H5商城,需要实现一个主页面底部 app-tab-menu
(控制首页、我的等页面的菜单导航)
因为将
app-tab-menu
放在 App.vue
中与<router-view>
同级,所以结合vue-router
及vuex
来实现以下效果:1.
app-tab-menu
中的页面匹配当前页面时 ,显示该元素,否则隐藏2.
app-tab-menu
对当前页面的item
呈现单独的.active
样式效果
以下即时简单的实现代码:
//
// App.vue
//
<template>
<div id="app">
<router-view/>
<div class="app-tab-menu" v-show="showAppTabMenu">
<router-link :to="{path:item.path}" class="app-tab-menu-item" v-bind:class="[item.pathName==currentPageName?'active':'']" v-for="item in appTabMenu">
<span class="icon" v-bind:class="[item.iconClass,item.pathName==currentPageName?'active':'']"></span>
<p class="name">{{item.name}}</p>
</router-link>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
appTabMenu:[
{name:'首页',pathName:'home',path:'/',iconClass:'icon-app-tab-menu-home'},
{name:'我的',pathName:'about',path:'/about',iconClass:'icon-app-tab-menu-my'},
],
}
},
computed:{
currentPageName(){ // 监听 store.state.currentPageName 的改变
return this.$store.state.currentPageName;
},
showAppTabMenu(){ // store.state.currentPageName 改变时,重新判断 app-tab-menu 是否需要显示
let current = this.$store.state.currentPageName;
let arr =this.appTabMenu.filter((v,i)=>{
return v.pathName == current;
});
return arr.length;
},
},
created() {
console.log('App.vue created()');
},
}
</script>
//
// store.js
//
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
currentPageName:'',// store.state.currentPageName 是 app-tab-menu 是否显示判断的关键
},
mutations: {
updatePageName(state,name){
if(typeof name == 'string' && name.length>0){
state.currentPageName = name;
}
}
},
})
//
// router.js
//
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import store from './store'
Vue.use(Router);
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '*',
name: '404',
component: () => import(/* webpackChunkName: "404" */ './views/404.vue')
},
{
path: '',
name: 'null',
redirect: { name: 'home' }
},
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
});
router.beforeEach((to,from,next)=>{
console.log(`${from.name} ==>> ${to.name}`);
store.commit('updatePageName',to.name);//路由改变时,显式的改变 store.state.currentPageName 状态值
next();
});
export default router;