Vuex收尾与项目开始
Vuex子组件
我们需要一个方法,将越来越多的action,mutation数据进行整合。vuex提供了子组件模式。
子组件定义
自定义一个对象,然后再对象当中编写vuex的属性:action,mutation,state,getters
最后将这个对象放到vuex的实例的modules下
import Vue from 'vue' import Vuex from 'vuex' import axios from '../utils/http' Vue.use(Vuex) const IndexStore = { state:()=>({ img_list:[] }), mutations: { BannerMutation(state,img_list){ state.img_list = img_list } }, actions: { BannerActions(context){ axios.get('/api/getbanner').then( res=>{ var list = res.data.list; context.commit('BannerMutation',list) } ) } } } export default new Vuex.Store({ modules: { IndexStore //IndexStore:IndexStore } })
调整文件结构
//在store目录下创建IndexStore,将关于index的vuex部分编写到这里 import axios from '../utils/http' const IndexStore = { state:()=>({ img_list:[] }), mutations: { BannerMutation(state,img_list){ state.img_list = img_list } }, actions: { BannerActions(context){ axios.get('/api/getbanner').then( res=>{ var list = res.data.list; context.commit('BannerMutation',list) } ) } } } export default IndexStore
在主文件导入使用
import Vue from 'vue' import Vuex from 'vuex' import IndexStore from './IndexStore' Vue.use(Vuex) export default new Vuex.Store({ modules: { IndexStore //IndexStore:IndexStore } })
由于嵌套,导致数据的层级发生了变化
map映射调用
state使用map
this.$store.state.模块.数据 computed: { ...mapState({'数据': state=>state.模块.数据}) },
action使用map
this.$store.dispath("模块/方法") methods: { ...mapActions('模块名称',['方法名称']) },
mutation使用map
this.$store.commit("模块/方法") methods: { ...mapMutations('模块名称',['方法名称']) },
getters使用map
this.$store.getters.模块.数据 computed: { ...mapGetters('模块名称',['方法名称']) },
页面布局
//使用postman查看接口
axios 响应拦截器
基于全局路由守卫,对登录进行校验
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const router = new VueRouter({ routes }) router.beforeEach(function(to,from,next){ //设置白名单 const no_login_list = ['/login'] if(no_login_list.indexOf(to.path) === -1){ //获取localstorage当中的token,校验是否存在 var tokenString = localStorage.getItem("login_data")||'{}' var token = JSON.parse(tokenString).token if(token){ next() }else{ next("/login") } }else{ next() } }) export default router