赞
踩
什么时候用:
多个组件依赖于统一状态
来自不同组件的行为需要变更同一状态
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')
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 })
组件中读取vuex数据: store.state.sum
组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)
或 $store.commit('mutations中的方法名',数据)
state中的数据需要加工再使用时,可以用getters
//准备getters——用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum*10
}
}
//创建store
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
组件中读取数据: $store.getters.bigSum
四个map方法的使用:(对象写法与数组写法)
computed:{
...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),
}
computed:{
...mapGetters(['bigSum'])
}
methods:{
...mapMutations({increment:'JIA',decrement:'JIAN'}),
}
methods:{
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
}
mapMutations与mapActions使用时,若需传参,在模板中绑定事件时传递好参数,否则参数是事件对象本身
d:‘jiaOdd’,incrementWait:‘jiaWait’})
}
mapMutations与mapActions使用时,若需传参,在模板中绑定事件时传递好参数,否则参数是事件对象本身
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。