vue正确的使用vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。现在大型项目基本上都需要使用vuex,所以专门写一遍如何配置与使用vuex供人探讨。

一、安装vuex

1、终端安装 npm install vuex --save

2、创建store文件夹,文件夹里新建index.js与modules文件夹(vuex模块化)

index.js代码如下:

import Vue from 'vue'
import Vuex from 'vuex'
//引入模块
import a from './modules/a'
import b from './modules/b'
import c from './modules/c
export default new Vuex.Store({
  state: {
    axiosCancel: []
  },
  mutations: {},
  actions: {},
  modules: {
    a,
    b,
    c
  }
})

modules里面放置store模块

比如a模块里面代码(namespaced作用:为了解决不同模块命名冲突的问题,将不同模块的namespaced:true,之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名)

const state = {

  basePath: 'homepage'
}

const mutations = {

  CHANGE_BASEPATH: (state, path) => {
    state.basePath = path
  }
}

const actions = {

  changeBasePath({ commit }, path) {
    commit('CHANGE_BASEPATH', path)
  }
}

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

3 main.js文件引入

代码如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from '@/store'
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

二、使用vuex

 新建一个demo代码如下:

<template>
  <div class="">a模块调用mutation的值:{{ basePath }}</div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  components: {},
  data() {
    return {
    }
  },
  computed: {
    ...mapState({
      'basePath': state => state.a.basePath
    })

  },
  watch: {},
  created() {
    // 使用a模块的state
    console.log(this.$store.state.a)
    // 使用a模块的mutation(不推荐这样写,推荐写成对象的形式{path:'qqqq'},这样可以传多个参)
    this.$store.commit('a/CHANGE_BASEPATH', 'qqqq')
    // 使用a模块的action
    this.$store.dispatch('a/changeBasePath', 'bbbb')
  },
  mounted() {},
  methods: {}
}
</script>
<style lang="scss" scoped>
</style>

把state放在computed里这样state的值改变dom的值也改变

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值