什么是vuex? 我理解的vuex就是数据和状态的管理
如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
五大核心:
const store = new Vuex.Store({
state: {
},
mutations: {
}
action:{
}
getter:{
}
module:{
}
})
1:state的使用:state是用来存储数据
如何读取数据?
读取数据最通用的方法就是计算属性。
computed: {
count () {
return this.$store.state.count
}
}
但是我们用map函数会简单方便读取数据 mapState
import { mapState } from 'vuex'
computed:{
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
2 mutation 这个是修改state中数据状态的唯一方法 ,说白了就是mutation提供方法来修改state中的数据,方法中可以传递参数,一个是state一个是payload ,payload是调用时候单文件组件中传递过来的数据
如何修改提交?
mutations: {
increment (state,payload) {
// 变更状态
state.count++
}
}
单文件组件中提交mutation中的方法
this.$store.commit('increment',{id:1})
提交increment 方法 并且传入参数{id:1}
mapmutation提交
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}