vue(Vuex子组件,scoped对某些css有影响)框架

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
​

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值