当前位置:   article > 正文

Vue第五章Vuex创建并引入store、getters的使用、四个map方法的使用_vuex中mapstore怎么用

vuex中mapstore怎么用

第五章:Vuex

什么时候用:

多个组件依赖于统一状态

来自不同组件的行为需要变更同一状态

vuex

创建并引入store

main.js下代码

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.use(Vuex)
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store,
}).$mount('#app')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

store文件夹下index.js代码

//该文件用于创建Vuex中最为核心的store

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//准备actions——用于相应组件中的动作
const actions = {}
//准备mutations——用于操作数据(state)
const mutations = {}
//准备state——用于存储数据
const state = {}

//创建store
export default new Vuex.Store({
    actions,
    mutations,
    state
})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

组件中读取vuex数据: store.state.sum

组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)

getters的使用

state中的数据需要加工再使用时,可以用getters

//准备getters——用于将state中的数据进行加工
const getters = {
    bigSum(state){
        return state.sum*10
    }
}
//创建store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

组件中读取数据: $store.getters.bigSum

四个map方法的使用:(对象写法与数组写法)

1、mapState:映射state中的数据为计算属性

 computed:{
     ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),
         }
  • 1
  • 2
  • 3

2、mapGetters:映射getters中的数据为计算属性

 computed:{
     ...mapGetters(['bigSum'])
         }
  • 1
  • 2
  • 3

3、mapMutations:用于生成与mutation对话的方法

   methods:{ 
    	...mapMutations({increment:'JIA',decrement:'JIAN'}),
    }
  • 1
  • 2
  • 3

4、mapActions:用于帮助我们生产与actions对话的方法

   methods:{ 
  		...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
      }
  • 1
  • 2
  • 3

mapMutations与mapActions使用时,若需传参,在模板中绑定事件时传递好参数,否则参数是事件对象本身

d:‘jiaOdd’,incrementWait:‘jiaWait’})
}


mapMutations与mapActions使用时,若需传参,在模板中绑定事件时传递好参数,否则参数是事件对象本身

  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/280252
推荐阅读
相关标签
  

闽ICP备14008679号