什么是Vuex? 为什么要使用Vuex ?vuex使用示例 (***数据持久化***)

在 Vue 项目中,如果项目结构简单,父子组件之间的数据传递可以使用 props 或者 $emit 等方式 (详参大神博文《Vue进阶(六):组件之间的数据传递》)。如果是大型项目,很多时候都需要在子组件之间传递数据,使用之前的方式就不太方便。Vue 的状态管理工具 Vuex 完美的解决了这个问题。

首先,我们需要知道 vue 是以单向数据流的方式驱动的。

  1. 多个视图依赖于同一状态。
  2. 来自不同视图的行为需要变更同一状态。
    vuex 类似Redux的状态管理器, 用来管理Vue的所有组件状态,采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

首先使用 npm 安装 Vuex

cnpm install vuex -S

然后在main.js中 引入store.js, 然后注入 store

import Vue from 'vue'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import ElementUI from 'element-ui'
import '@/styles/index.scss' // global css
import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n
import App from './App'
import store from './store'
import router from './router'
import i18n from './lang'
import '@/icons' // icon
import '@/permission' // permission control
import * as filters from './filters' // filters
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.use(ElementUI, {
  locale,
  i18n: (key, value) => i18n.t(key, value)
})
Vue.config.productionTip = false
new Vue({
  el: '#app',
  router,
  store,
  i18n,
  render: h => h(App)
})

创建store目录如下
在这里插入图片描述

getters.js文件内容

const getters = {
  notiedInfo: state => state.app.notiedInfo, //选中的未绑卡信息
  tiedInfo: state => state.app.tiedInfo, //选中的已绑卡信息
  extInfo: state => state.app.extInfo, //支付页信息
  orderInfo: state => state.app.orderInfo, //支付页信息
}
export default getters

index.js文件内容

import getters from './getters'
import app from './modules/app'
import calculater from './modules/calculater'
import part from './modules/loadInsurance'
import car from './modules/car'
import Vuex from 'vuex'
import Vue from "vue";
import createPersistedState from "./plguins/prisist"

Vue.use(Vuex)
const store = new Vuex.Store({
//数据持久存储代码start
    plugins: [createPersistedState({
        priset: [
            {
                name: "orderInfo",
                type: "app/TOGGLE_PAGES_ORDER_INFO"
            },
            {
                name: "extInfo",
                type: "app/TOGGLE_PAGES_EXT_INFO"
            },
            {
                name: "tiedInfo",
                type: "app/TOGGLE_PAGES_TIED_INFO"
            },
            {
                name: "notiedInfo",
                type: "app/TOGGLE_PAGES_NOTIED_INFO"
            }
        ]
    })],
    //数据持久化代码end
    modules: {
        app,
        car,
        calculater,
        part
    },
    getters
})
export default store

app.js文件内容

const state = {
  orderInfo: { //收银台顶部模块
    orderAmount:'', //支付金额
    orderDescription:'', //商品名称
    orderDetailUrl:'', //查看订单详情
    outOrderId:'', //订单编号
  },
  extInfo: {//查看详情链接所需参数
    t_InsuredName:'',
    identificationNumber:'',
    isNewCar:'',
    orderDetailParam:'',
    orderDetailDomain:'',
  },
  tiedInfo: { //选中的已绑卡信息
    bankCode:'',//银行卡code
    bankcardType:'',//银行卡类型
    storablePan:'',//银行缩略号
    shortPhoneNo:'',//手机缩略号
    cellPhone:'',//手机号
    url:''//银行卡图片路径
  },
  notiedInfo: {//选中的未绑卡信息
    bankCode:'',//银行卡code
    bankName:'',
    url:''//银行卡图片路径
  }
}

const mutations = {
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  TOGGLE_RELOAD_KEY: (state) => {
    state.reloadKey = state.reloadKey + 1
  },
  TOGGLE_NATION: (state, nation) => {
    state.nationSelectList = nation
  },
  TOGGLE_PAGES_GLOBAL_INFO: (state, info) => { // 页面全局使用信息
    Object.keys(info).map((key)=> {
      state.globalInfo[key] = info[key]
    })
  },
  TOGGLE_PAGES_ORDER_INFO: (state, info) => { // 页面全局使用信息
    Object.keys(info).map((key)=> {
      state.orderInfo[key] = info[key]
    })
  },
  TOGGLE_PAGES_EXT_INFO: (state, info) => { // 页面全局使用信息
    Object.keys(info).map((key)=> {
      state.extInfo[key] = info[key]
    })
  },
  TOGGLE_PAGES_TIED_INFO: (state, info) => { //选中的已绑卡信息
    Object.keys(info).map((key)=> {
      state.tiedInfo[key] = info[key]
    })
  },
  TOGGLE_PAGES_NOTIED_INFO: (state, info) => { //选中的未绑卡信息
    Object.keys(info).map((key)=> {
      state.notiedInfo[key] = info[key]
    })
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  getNationSelectList({ commit }) {
    return import('@/utilis/nation.constant.js').then((data)=> {
      commit('TOGGLE_NATION', data.nationList)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

pay.vue页面

import { mapGetters } from 'vuex'
  export default {
    name: "payment",
    components: {
        OverTimePage,
        QuestionPrompt,
        SlideBoxpay
    },
    data: function () {
        return {
            extInfos: [],
        }
    },
    computed: {
        ...mapGetters([
            'orderInfo',
            'extInfo'
        ])
    },
    methods:{
     // vm.extInfo = extInfo
	store.commit('app/TOGGLE_PAGES_EXT_INFO', {
	t_InsuredName: extInfo.t_InsuredName,
	identificationNumber: extInfo.identificationNumber,
	isNewCar: extInfo.isNewCar,
	orderDetailParam: extInfo.orderDetailParam,
	orderDetailDomain: extInfo.orderDetailDomain
	}),
	// vm.orderInfo = data.orderInfo
	store.commit('app/TOGGLE_PAGES_ORDER_INFO', {
	orderAmount: data.orderInfo.orderAmount,
	orderDescription: data.orderInfo.orderDescription,
	orderDetailUrl: data.orderInfo.orderDetailUrl,
	outOrderId: data.orderInfo.outOrderId
	})
    }
 }

prisist.js 文件内容


export default function (config) {

    return function createPersistedState(store) {
        config.priset.forEach(item =>{
            let name = window.localStorage.getItem(item.name)
            if (name){
                name = JSON.parse(name)
                store.commit(item.type, name)
            }
        })
        store.subscribe(mutation => {
            config.priset.forEach(item =>{
                if (mutation.type === item.type) {
                    window.localStorage.setItem( item.name,JSON.stringify(mutation.payload) )
                }
            })
        })

    }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值