1.创建 store 结构
2.main.js 引入 vuex
3. App.vue 组件使用 vuex
<template> <div id="app"> <loading v-show="loading"></loading> <NavView v-show="headerShow"></NavView> <router-view></router-view> <FooterView></FooterView> </div> </template> <script> /** * 引入 组件 */ // 头部导航 import NavView from './components/Nav.vue' // 底部选项卡 import FooterView from './components/Footer.vue' // 引入 vuex 的两个方法 import {mapGetters, mapActions} from 'vuex' export default { // 计算属性 computed:mapGetters([ // 从getters中获取headerShow的值 'headerShow', 'loading' ]), watch:{ // 监听,当路由发生变化的时候执行 $route(to,from){ if(to.path == '/user-info'){ /** * $store来自Store对象 * dispatch 向 actions 发起请求 */ this.$store.dispatch('hideHeader'); }else{ this.$store.dispatch('showHeader'); } } }, components:{ NavView, FooterView } } </script> <style lang="scss"> @import './assets/css/index.css'; </style>
4.store
(1)index.js 入口文件
/** * 步骤一 * vuex入口文件 */ // 引入 vue import Vue from 'vue' // 引入 vuex import Vuex from 'vuex' import actions from './actions' import mutations from './mutations' Vue.use(Vuex); export default new Vuex.Store({ modules:{ mutations }, actions });
(2)type.js 状态(类型)
/** * 步骤二 * types 状态(类型) */
(3)actions.js 管理事件(行为)
/** * 步骤三 * actions 事件(行为) */ // 导出 export default{ showHeader:({commit}) => { // 提交到 mutations commit('showHeader'); }, hideHeader:({commit}) => { // 提交到 mutations commit('hideHeader'); }, showLoading:({commit}) => { commit('showLoading'); }, hideLoading:({commit}) => { commit('hideLoading'); } }
(4)mutations.js 突变
/** * 步骤四 * mutations 突变 */ // 引入 getters import getters from './getters' // 定义、初始化数据 const state = { header:true, loading:false }; // 定义 mutations const mutations = { // 匹配actions通过commit传过来的值,并改变state上的属性的值 showHeader(state){ state.header = true; }, hideHeader(state){ state.header = false; }, showLoading(state){ state.loading = true; }, hideLoading(state){ state.loading = false; } } // 导出 export default { state, mutations, getters }
(5)getters.js 获取数据
/** * 步骤五 * getters 获取数据 */ // 导出 export default{ headerShow:(state) => { return state.header; }, loading:(state) => { return state.loading; } }
.