vuex使用场景(Vuex怎么使用)

1 安装vuex

npm install vuex -S2 导入vuex

import Vuex from "vuex"Vue.use(Vuex)创建store对象

const store = new Vuex.Stroe({ state : { count : 0 }});4将store对象挂载到vue实例中

new Vue({ el : '#app' render: h => h(app), router, store})主要核心概念StateMutationActionGetterState

State提供唯一的公共数据源, 所有共享的数据都要统一放到Store的State中存储



const store = new Vuex.Stroe({ state : {count : 0}});

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



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

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



// 从vuex中导入mapState函数import {mapState} from 'vuex

通过导入mapState函数, 将当前组件需要的全局数据 映射为当前组件的computed计算属性



computed: { …mapState(['count'])}Mutaion

mutaion用于变更store中的数据

只能通过mutation变更Store中的数据, 不可以直接操作Store中的数据通过这种方式虽然操作起来繁琐一些,但是可以集中监控所有数据的变化

// 定义mutationconst store = new Vuex.Store({ state : {count: 0}, mutations: { add(state){ state.count++ } }})//触发mutationmethods: { handler(){ this.$store.commit('add') }}

commit的作用就是调用某个mutation

mutatitons传递参数

mutations:{ //定义 addN(state, step){ state.count += step }}//触发mutationmethods: { handler(){ //触发时携带参数 this.$store.commit('addN', 3) }}

触发mutations的第二种方式



//从vuex中按需导入mapMutations函数import {mapMutations} from 'vuex'

通过导入的mapMutations函数,将需要的函数映射为当前组件的methods



methods: { …mapMutations(['add', 'addN'])}//调用this.addN(3)Action

Action用于处理异步任务


如果通过异步操作变更数据,必须通过Action,而不能使用mutation,但是在Action中还是通过触发mutaion的方式间接变更数据



const store = new Vuex.Store({ // 只有mutations中定义的函数才能修改state的数据 mutations : { add(state){ state.count ++; } }, actions:{ addAsync(context){ // 在action中不能直接修改sate中的数据,必须通过context.commit()触发mutation setTimeout(() => { context.commit('add') }, 1000); } }})//触发actionmethods: { handler(): { this.$store.dispatch('addAsync') }}

触发actions携带参数



const store = new Vuex.Store({ state: {count: 0}, mutations: { addN(state, step){ state.count += step } }, actions:{ addNAsync(context, step){ setTimeout(() => { context.commit('addN', step) }, 1000) } }})//触发actionmethods: { handle(){ this.$store.dispatch('addNAsync', 5) }}Getter

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

getter可以对store中已有的数据进行加工处理形成行的数据, 类似Vue的计算属性store中的数据发生变化 getter中的数据也会发生相应的变化

//定义getterconst store = new Vuex.Store({ state : {count: 0}, getters: { showNUm(state){ return '当前最新的数据是' +state.count; } }});

使用Getter的方式 一



this.$store.getters.showNUm

第二种方式



import {mapGetters} from 'vuex'computed: { …mapGetters(['showNum'])}

本站部分内容由互联网用户自发贡献,该文观点仅代表作者本人,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如发现本站有涉嫌抄袭侵权/违法违规等内容,请联系我们举报!一经查实,本站将立刻删除。