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