- vuex是一个专门为vue.js提供的状态管理模式,个人理解是统一管理数据,因为vue是数据驱动视图,当客户输入数据后也会改变状态,状态改变了意味着数据改变,所以有一个三者关系(图片摘自官网)
官网上是这样说的: - state,驱动应用的数据源;
- view,以声明方式将 state 映射到视图;
- actions,响应在 view上的用户输入导致的状态变化。
- ``
具体步骤是首先建立一个store.js
store.js
import vue from "vue"
import vuex from "vuex"
vue.use(Vuex)
let store = new Vuex.store({
state={
count:0;
list:[{name:"ting",age:20},{name:"ting",age:22}]
}
getters:{
filterlist:state=>{
return state.list.filter(item=>item.age>20)
}
}
action()
})
//在main.js中
import store from “@/store.js”
new vue({
el:"#app",
store,
})
//list.vue
由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态
<template>
<div id='wrap'>
{{ count}} // 0
{{filterlist}} // [{name:"ting",age:22}]
</div>
</template>
import {mapState} from 'vuex'
computed: {
第一种获取counts值的方法:
count() {
return this.$store.state.count
}
第二种获取counts值的方法
...mapState(["count"])
//第一种或获取filterlist 的方法
filterlist(){
return this.$store.getters.filterlist
}
//第二种或获取filterlist 的方法把computed的{}删了把下面的代码当属性值
mapGetters([
'doneTodos', 'doneTodosCount', 'getTodoById'
])
}
//为什么通过this.
store 访问到
//mutations是个同步函数(同步的原因是异步的话会造成程序调试困难),是改变state的唯一方法
你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
incrementBy (state) {
state.count --
}
}
});
组件中
<template>
<div id='wrap'>
{{ count}} //0 1 2 ...会根据点击的次数依次加一
<button @click=''increment''>点击</button>
<button @click=''incrementBy''>点击</button> ...会根据点击的次数依次减 一
</div>
</template>
import { mapState, mapMutations } from 'vuex';
computed: mapState([
'count'
]),
methods: mapMutations([
'increment',
'incrementBy'
])
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
//此处的context指的是与 store 实例具有相同方法和属性的对象也可以写成context.state context.getters....
increment (context) { //context可以解构成{commit}
context.commit('increment') // commit('increment')
}
}
})
action需要store.dispatch的方法来触发
组件中可以在methods中
…mapActions([
‘increment’, // 将 this.increment()
映射为 this.$store.dispatch('increment')
先说这些 因为还没搞懂下面的所以没写