美文网首页
vue结合vuex

vue结合vuex

作者: 搬个菠萝晒太阳 | 来源:发表于2019-03-01 11:50 被阅读0次

    在src目录下面,新建一个store文件夹,目录结构如下


    image.png

    1、index文件

    import Vue from 'vue'
    import Vuex from 'vuex'
    import mutations from 'store/mutations'
    import state from 'store/state'
    import getters from 'store/getters'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state,
      mutations,
      getters
    })
    

    2、state文件

    const userInfo = JSON.parse(window.localStorage.getItem('user-info')) || ''
    const user = {
      isLogin: userInfo.isLogin ? userInfo.isLogin : false,
      username: userInfo.username ? userInfo.username : '',
      token: userInfo.token ? userInfo.token : ''
    }
    export default {
      haveTabbar: true,
      cartList: JSON.parse(window.localStorage.getItem('cart-lists')) || [],
      searchLists: JSON.parse(window.localStorage.getItem('search-lists')) || [],
      user
    }
    

    3、mutation文件(计算新的值)

    export default{
    //修改state的方法
    }
    

    4、getters文件

    export default {
      totalCount (state) {
        if (state.user.isLogin === false) {
          return 0
        } else {
          return state.cartList.reduce((result, list) => {
            result += list.count
            return result
          }, 0)
        }
      },
      totalPrice (state) {
        return state.cartList.reduce((result, list) => {
          if (list.isChecked) {
            result += list.count * list.price
          }
          return result
        }, 0)
      },
      totalCheckCount (state) {
        return state.cartList.reduce((result, list) => {
          if (list.isChecked) {
            result += list.count
          }
          return result
        }, 0)
      },
      changeAllState (state) {
        if (state.cartList.length === 0) {
          return false
        } else {
          return state.cartList.every(list => list.isChecked === true)
        }
      }
    }
    
    

    相关文章

      网友评论

          本文标题:vue结合vuex

          本文链接:https://www.haomeiwen.com/subject/phxduqtx.html