vuex 修改state中的数据操作


1、state 中的数据,是能可以直接写方法methods修改的,注意:是不推荐这种方式修改

    1、直接修改,就会不安全

    2、每个组件实例,都可以通过 this.$store 来访问store对象里的共享数据

 

2、修改操作state的数据,要通过mutations,在里面写方法【同步操作】

    1、所有的数据的操作,不在外面操作,都是在vuex里面操作

    2、对于外界组件,通过commit来操作

 methods: {
    onClick() {
      
      this.$store.commit('increment' , {step: 3});
      
    },

 

3、异步修改操作,state共享数据

 

 actions: {
    // action方法的第1个参数为上下文数, 通过context下state或commit操作state状态
    
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment');
      }, 1000);

    },
 onClickAsync() {
      // 方式1:
      this.$store.dispatch('incrementAsync')
      
      this.add({step: 200});
      
    },

 读取state,中共享数据的方式

    方式一:直接访问

  方式一:直接访问
  computed:{
    count() {
      return this.$store.state.count;
    },
    length() {
      return this.$store.state.list.length;
    }
  }
总结:这种访问方式,代码比较繁琐

    方式二:通过vuex中的,mapState函数访问(推荐)

方式二: mapState函数
  computed: mapState(['count', 'list'])
  computed: {
    // 本地computed属性
    
    ...mapState(['count', 'list'])     //通过解构,直接拿值
    ...mapState({
      // 如果与本地名有冲突,读取state的值并取别名
      stateCount: state => state.count,
      commodities: 'list'
    }),

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM