vuex必备基础知识

405 阅读1分钟

1.Vuex概述

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

使用Vuex管理数据的好处:
A.能够在Vuex中集中管理共享数据,便于开发和后期进行维护
B.能够高效实现组件之间数据共享,提高开发效率
C.储存在Vuex中的数据是响应式的,当数据发生变化,页面中的数据也会同步更新

2.State

State提供唯一的公共数据源,所有的数据都要统一放到store中的state储存
// 创建一个store数据源,提供一个公共数据
const store = new Vuex.store({
	state: { count: 0 }
})

组件访问state中数据第一种方式:
this.$store.state.全局数据名称

组件访问state中数据第二种方法
// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的的全局数据,映射为当前组件的computed计算属性:
// 2.将全局数据,映射为当前组件的计算属性
computed: {
	...mapState(['count'])
}
ps: 插值表达式中写count,即可在在页面渲染出数据

3.Mutation

Mutation 用于变更store中数据。
1️⃣只能通过mutation变更store中数据,不可以直接操作store中数据
2️⃣通过这种方式变更的数据,可以监控所有变化的数据

变更state中数据第一种方式:
// 1.定义mutation
cosnt store = new Vuex.Store({
	state: {count: 0}
})
mutations:{
	add(state) {
    	// 变更状态
    	state.count ++
    }
}

// 2.触发mutation
methods: {
	handle1(){
    	// 触发mutation的第一种方式
        this.$store.commit('add')
    }
}

可以触发mutation时传递参数:
// 定义mutation
cosnt store = new Vuex.Store({
	state: {count:0}
})
mutation: {
	addN(state, step) {
    	// 变更状态
        state.count += step
    }
}

// 触发mutation
methods: {
	handle2(){
    	this.$store.commit('addN', 3)
    }
 }


变更state中数据第二种方式:
// 1.从vuex中按需导入mapMutation函数
import{ mapMutation }from 'vuex'

ps:通过刚才导入的mapMutation函数,将需要的mutations函数,映射为当前组件的methods方法

// 2.将指定mutations函数,映射为当前组件的methods函数
methods: {
	...mapMutation(['add', 'addN'])
}

4.Action

Action用于处理异步任务
如果痛殴异步操作变更数据,必须通过Action,不能痛殴使用gmutation,但是Action中还是要通过触发
mutation的方式间接变更数据。

间接变更数据的第一种方式:(不携带参数)
// 定义 Action
const store = new Vuex.Store({
	// ....省略其他代码
    mutations: {
    	add(stata) {
        	state.count ++
        }
    },
    actions: {
    	addAsync(context) {
        	setTimeout(() => {
            	context.commit('add')
            }, 1000)
        }
    } 
})

// 触发Action
methods:{
	handle(){
    	this.$store.dispath('addAsync')
    }
}

// 触发actions异步任务时候携带参数
// 定义Action
const store = new Vuex.Store({
	// ....省略其他代码
    mutations: {
    	addN(state, step) {
        	state.count += step
        }
    },
    actions: {
    	addNAsync(context) {
        	setTimeout(() => {
            	context.commit('addN', step)
            }, 1000)
        }
    }
})
// 触发Action
methods: {
	handle() {
    	// 在调用dispath函数
        // 触发 actions是携带参数
        this.$store.dispath('addNAysnc', 5)
    }
}

// 触发actions异步任务时第二种方式:
// 1.从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'

通过刚才导入mapActions函数,将需要的actions函数,映射为当前组件的methods方法
mmethods: {
	...mapActions(['addAsync', 'addNAsync'])
}

5.Getter

Getter用于对store中数据进行加工处理形成新的数据
1️⃣Getter可以对store中数据加工处理形成新的数据类似vue中计算属性
2️⃣store中数据变化,gette中中数据也会发生变化
// 定义Getter
const store = new Vuex.Store({
	state: {count: 0}
    // 省略 mutations actions代码
    getters: {
    	showNum: state => {
        	return `当前getter之后的数据¥¥${state.count}`
        }
     }
})

使用getters的第一方式:
this.$store.getter.名称

使用getters的第二种方式:
import { mapGetters } from 'vuex'
computed: {
	...mapGetters(['showNum'])
}

完整案例 代码

 // store/index.js
 import Vue from 'vue'
 import Vuex from 'vuex'

 Vue.use(Vuex)

 export default new Vuex.Store({
   state: {  // 全局共享的数据
     count: 0
   },
   mutations: { // 只能执行同步操作 只有mutations中函数才有权限修改state中的值
     increment1 (state) {
       state.count ++
     },
     increment2 (state, step) {
       state.count += step
     },
     sub(state) {
       state.count --
     },
     subN(state, step) {
       state.count -= step
     }
   },
   actions: { // 专门异步操作
     addAsync(context) {
       setTimeout(() => {
         // 在action中不能直接修改state中数据
         context.commit('increment1')
       }, 1000)
     },
     addNAsync(context, step) {
       setTimeout(() => {
         // 在action中不能直接修改state中数据
         context.commit('increment2', step)
       }, 1000)
     },
     subAsync(context) {
       setTimeout(() => {
         context.commit('sub')
       },1000)
     },
     subNAsync(context, step) {
       setTimeout(() => {
         context.commit('subN', step)
       },1000)
     }
   },
   getters: {
     showNum(state) {
       return '当前最新的数量是【$$' + state.count + '】' 
     }
   },
   modules: {
   }
 })
 // componnets/additions.vue
     <template>
     <div class="hello1">
       <!-- <p>当前最新的值:{{$store.state.count}}</p> -->
       <h2>{{$store.getters.showNum}}</h2>
       <button @click="add1">+1</button>
       <button @click="add2">+N</button>
       <button @click="add3">+1 Async</button>
       <button @click="add4">+N Async</button>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {}
     },
     methods: {
       add1() { // 不带参数
         this.$store.commit('increment1')
       },
       add2() {
         this.$store.commit('increment2', 3)
       },
       add3() {
         this.$store.dispatch('addAsync')
       },
       add4() {
         this.$store.dispatch('addNAsync', 5)
       }
     }
   }
   </script>
components/subtraction.vue
    <template>
      <div class="hello">
        <!-- <p>当前最新的值:{{count}}</p> -->
        <h2>{{showNum}}</h2>
        <button @click="sub1">-1</button>
        <button @click="sub2">-N</button>
        <button @click="sub3">-1 Async</button>
        <!-- <button @click="subAsync">-1 Async</button> -->
        <button @click="sub4">-N Async</button>
      </div>
    </template>

    <script>
    import { mapState, mapMutations, mapActions,mapGetters } from 'vuex'
    export default {
      data() {
        return {}
      },
      computed: {
        ...mapState(['count']),
        ...mapGetters(['showNum'])
      },
      methods: {
        ...mapMutations(['sub', 'subN']),
        ...mapActions(['subAsync', 'subNAsync']),
        sub1() {
          this.sub()
        },
        sub2() {
          this.subN(3)
        },
        sub3() {
          this.subAsync()
        },
        sub4() {
          this.subNAsync(5)
        }
      },
    }
    </script>