1. 首页
  2. 软件开发
  3. Vuex详解

Vuex详解

  • 发布于 2024-08-19
  • 13 次阅读

Vuex是什么:

Vuex是实现组件全局状态(数据)管理的一种机制,它采用集中式存储管理应用的所有组件的状态,可以方便的实现组件之间的数据共享。

什么时候使用vuex:

如果您的应用够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。引用 Redux 的作者 Dan Abramov 的话说就是:

Flux 架构就像眼镜:您自会知道什么时候需要它。---摘自官网

vuex统一管理状态的好处:

  1. 能够在vuex中集中管理共享的数据,有助于开发和后期的维护;
  2. 能够高效的实现组件之间的数据共享,提高开发效率;
  3. 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步;

vuex的安装:

  1. 安装vuex依赖包
npm install vuex --save
  1. 新建store文件夹,新建index.js文件,导入vuex包
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
  1. 创建store对象
export default new Vuex.Store({
   
  
})
  1. 将 store 对象挂载到 vue 实例中
import store from './store'

new Vue({
   
  el: '#app',
  render: h => h(App),
  router,
  // 将创建的共享数据对象,挂载到 Vue 实例中
  // 所有的组件,就可以直接用 store 中获取全局的数据了
  store
})

state数据源:

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

// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
   
   state: {
   
      count: 0
   }
})

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

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

注意:在template中,不用添加this

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

1.从 vuex 中按需导入 mapState 函数

import {
    mapState } from 'vuex'

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

computed: {
   
    ...mapState(['count'])
}

实例:

1.打开 store/index.js 文件,定义 count:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
   
  state: {
   
    count: 0
  },
  mutations: {
   
  },
  actions: {
   
  },
  modules: {
   
  }
})

2.在 components 目录下新建 increase.vue 文件:(通过第一种方式访问)

<template>
  <div>
    <h3>当前最新的Count值为:{
   {
   $store.state.count}}</h3>
    <button>+1</button>

  </div>
</template>
<script>
export default {
   
  name: "increase",
  data(){
   
    return{
   

    }
  },
  methods:{
   
    handleAdd(){
   

    },
  }
}
</script>

<style scoped>

</style>

3.subtraction.vue文件:(通过第二种方式访问)

<template>
  <div>
    <h3>当前最新的Count值为:{
   {
   count}}</h3>
    <button>-1</button>
  </div>
</template>
<script>
import {
    mapState } from 'vuex'

export default {
   
  name: "subtraction",
  data(){
   
    return{
   }
  },
  //定义一个计算属性
  computed: {
   
    ...mapState(['count'])  // 用...展开运算符把Count展开在资源属性里
  }
}
</script>

<style scoped>

</style>

4.在router/index.js中引入上述两个组件

//引入组件
import increase from "@/components/increase";
import subtraction from "@/components/subtraction";
//创建路由对象并配置路由规则
export default new Router({
   
    routes: [
        {
   path: '/increase', name: 'increase', component: increase},
        {
   path: '/subtraction', name: 'subtraction', component: subtraction},
    ]
})

Mutations:变更store数据源中的数据

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

强调: 只有 mutations里的函数,才有权利修改 state 的数据;而且 mutations里不能包含异步操作。

this.$store.commit() 触发

1.打开 store/index.js 文件,定义 count:

export default new Vuex.Store({
   
    state: {
   
        count:0,
    },
    //在定义Mutation计算属性,变更store中的数据
    mutations: {
   
        add (state) {
   
            // 变更状态
            state.count++
        },
        //增加一个+N的按钮并增加点击事件:
        addN(state,step){
   
		    // 变更状态
		    state.count += step
 		},
    }
})
  1. increase.vue 文件:(通过第一种方式触发)
<template>
  <div>
    <h3>当前最新的Count值为:{
   {
   $store.state.count}}</h3>
    <button @click="handleAdd">+1</button>
    <button @click="handleAdd2">+N</button>
  </div>
</template>
<script>
export default {
   
  name: "increase",
  data(){
   
    return{
   

    }
  },
  methods:{
   
    handleAdd () {
   
      // 触发 mutations 的第一种方式
      this.$store.commit('add')
    },
    handleAdd2 () {
   
      // commit 的作用,就是调用某个 mutation 函数
      this.$store.commit('addN', this.num)
    }
  }
}
</script>

<style scoped>

</style>

触发 mutations 的第二种方式:

1.从vuex中按需导入 mapMutations函数

import {
   mapMutations} from 'vuex'

2.通过刚才按需导入的 mapMutations函数,映射为当前组件的methods函数。

// store【简写】
mutations: {
   
  sub(state) {
   
    state.count--
  },
  subN(state, step) {
   
    state.count -= step
  }
},

// subtraction.vue文件【简写】
import {
    mapState,mapMutations } from 'vuex'
methods:{
   
  ...mapMutations(['sub','subN']),
  decrement(){
   
    // 调用 
    this.sub()
  },
  decrementN(){
   
    this.subN(5)
  }
}

Actions 处理异步操作

如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。
注意:在Actions 中不能直接修改 state中的数据,要通过 mutations修改。

// 定义 Action
export default new Vuex.Store({
   
  // ...省略其他代码
  mutations: {
   
  	// 只有 mutations中的函数才有权利修改 state。
    // 不能在 mutations里执行异步操作。
    add (state) {
   
      state.count++
    }
  },
  actions: {
   
    addAsync (context) {
   
      setTimeout(() => {
   
        // 在 actions 中,不能直接修改 state 中的数据
        // 必须通过 context.commit() 触发某个 mutations 的函数才行
        context.commit('add')
      }, 1000)
    },
    addNAsync (context, step) {
   
      setTimeout(() => {
   
        context.commit('addN', step)
      }, 1000)
    },
    
    subAsync (context) {
   
      setTimeout(() => {
   
        context.commit('sub')
      }, 1000)
    },
    
  }
})

this.$store.dispatch 触发 Actions

// 触发 Action
// ...省略其他代码
<button @click="handleAdd3">+1 Async</button>
<button @click="handleAdd4">+N Async</button>
methods: {
   
  handleAdd3 () {
   
      // 触发 actions 的第一种方式
      this.$store.dispatch('addAsync')
  },
  handleAdd4 () {
   
      // 在调用 dispatch 函数,触发 actions 时携带参数
      this.$store.dispatch('addNAsync', 5)
    }
}

触发 actions 的第二种方式:

定义:

1.从 vuex 中按需导入 mapActions 函数

import {
    mapActions } from 'vuex'

2.通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

methods: {
   
  ...mapActions(['subAsync', 'subAsync '])
}

实例:

// 触发 Action
// ...省略其他代码
<button @click="handleSub3">-1 Async</button>
<script>
import {
    mapActions } from 'vuex'
export default {
   
  methods: {
   
    ...mapActions(['subAsync']),
    handleSub3 () {
   
      this.subAsync()
    },
  }
}
</script>

Getter 对 Store中的数据进行加工处理形成新的数据。

Getter 不会修改 Store 中的原数据,它只起到一个包装器的作用,将Store中的数据加工后输出出来。

1.Getter可以对 Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
2.Store中数据发生变化, Getter 的数据也会跟着变化。

export default new Vuex.Store({
   
  // ...省略其他代码
 state:{
   
	count:0
  },
  getters: {
   
    showNum(state) {
   
      return '当前最新的数量是【' + state.count + '】'
    }
  },
})

通过 this.$store.getters.名称 访问

this.$store.getters.名称

mapGetters 映射为计算属性

//.....省略部分代码
<h3>{
   {
   showNum}}</h3>
import {
    mapGetters } from 'vuex'

computed:{
   
	...mapGetters(['showNum'])
}

最终练习项目代码已放入gitee中:

记得点个star呦: https://gitee.com/DZ_QY/vuex-demo.git

原文链接: https://blog.csdn.net/friggly/article/details/123637237