vue中的状态管理工具vuex

  • 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. s t o r e . s t a t e g e t t e r s s t o r e . j s m a i n . j s s t o r e s t o r e s t o r e t h i s . store.state或者getters就可以获取store.js中的数据呢?原因是我们在main.js中将store在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 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')
先说这些 因为还没搞懂下面的所以没写

猜你喜欢

转载自blog.csdn.net/weixin_42446516/article/details/90725781