Vuex的属性及基本用法

1.state:提供唯一的公共数据源,所有共享的数据统一放到Store的state中进行存储。

组件访问State中数据的第一种方式:

this.$store.state.全局数据名称

组件访问State中数据的第二种方式:

// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapState(['全局数据名称'])
}

2.mutation:用于变更Store中的数据

①只能通过mutation变更Store数据,不可以直接操作Store中的数据。

②通过这种方式虽然操作起来稍微繁琐,但是可以集中监控所有数据的变化。

③可以在触发mutations时传递参数 第二个参数。

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {    //  add(state, step)
      //变更状态
      state.count++   // state.count += step
    }
  }
})
//触发mutation 
methods: {
  handel() {
     this.$store.commit('add')  // this.$store.commit('add', 4)
  }
}


触发mutations的第一种方法:

this.$store.commit()

触发mutations的第二种方法:

// 1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapMutations(['方法名'])
}

3.action:用来处理异步任务

在Aciton中通过触发Mutation的方法间接变更数据。

用法:

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {    //  add(state, step)
      //变更状态
      state.count++   // state.count += step
    }
  },
  actions: {
    addAsync(context) {   // addAsync(context, step)
      setTimeout(() => {
        context.commit('add')  // context.commit('add', 3)
      }, 1000)
    }
  }
})
//触发mutation 
methods: {
  handel() {
     this.$store.dispatch('add')  // this.$store.dispatch('add', 4)
  }
}


触发actions的第一种方法:

this.$store.dispatch()

触发actions的第二种方法:

// 1.从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapActions(['方法名'])
}

4.getter:用于对store中的数据进行加工处理形成新的数据。

①getter 可以对store中已有的数据加工处理形成新的数据。

②store中数据发生变化,getter的数据也会跟着变化。

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  getters: {
   showNum(state) {
     return '当前最新的数据是:'+state.count
   }
  }
})

触发getters的第一种方法:

this.$store.getters.方法

触发actions的第二种方法:

// 1.从vuex中按需导入mapGetters函数
import { mapGetter } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapGetter(['方法名'])
}

5.module:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

猜你喜欢

转载自blog.csdn.net/Quentin0823/article/details/131478184