当前位置:首页 > 技术分析 > 正文内容

vuex的五个属性及使用方法示例(vuex的几个属性及其作用)

ruisui8812小时前技术分析1

Vuex是Vue.js的状态管理库,它通过中心化的状态管理使得组件间的数据共享更加容易。

Vuex包含五个核心属性:state、getters、mutations、actions和modules。

1:state:定义了应用程序的状态,就是我们要管理的数据。

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


2:getters:用于获取state中的数据,类似于计算属性。getters接收state作为第一个参数。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }
})

3:mutations:用于修改state中的数据,是唯一可以修改state的地方。mutations接收state作为第一个参数,接收payload作为第二个参数。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    },
    add(state, payload) {
      state.count += payload
    }
  }
})

4:actions:用于异步操作和提交mutations,在actions中可以进行任何异步操作,最后再提交到mutations中同步修改state。actions接收context作为第一个参数,其中包含了state、getters和commit等属性。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
  }
})

5:modules:用于将store分割成模块,每个模块中有自己的state、getters、mutations和actions。

const store = new Vuex.Store({
  modules: {
    cart: {
      state: {
        items: []
      },
      mutations: {
        addItem(state, item) {
          state.items.push(item)
        }
      },
      actions: {
        addAsyncItem(context, item) {
          setTimeout(() => {
            context.commit('addItem', item)
          }, 1000)
        }
      }
    }
  }
})


使用方法:

1:安装Vuex:npm install vuex --save

2:在main.js中,导入Vuex,并使用Vue.use()方法注册Vuex。

import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})
new Vue({
  store,
  render: h => h(App)
}).$mount('#app')


3:在组件中使用vuex中的数据和方法。

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment')
    }
  }
}
</script>







Vuex是Vue.js官方提供的状态管理库,用于管理Vue.js应用程序中的数据。

Vuex的五个属性分别是:state、mutations、actions、getters和modules。

1:state:用于存储Vuex应用程序的所有状态。它是一个JavaScript对象,包含多个键值对。

使用方法示例:

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


2:mutations:用于修改state中的数据。由于Vuex的状态是响应式的,所以所有的mutation方法都是同步的。

使用方法示例:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    },
    decrement (state) {
      state.count--
    }
  }
})


3:actions:用于处理异步操作或批量操作mutation。action方法接收一个context对象,包含state、commit和dispatch等方法。

使用方法示例:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    incrementAsync (context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
  }
})


4:getters:用于对store中的数据进行计算和过滤。它类似于Vue.js中的计算属性。

使用方法示例:

const store = new Vuex.Store({
  state: {
    todos: [
      {id: 1, text: 'Learn Vue', done: true},
      {id: 2, text: 'Build an app', done: false},
      {id: 3, text: 'Deploy to production', done: false}
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})


5:modules:将store分割成模块,每个模块都拥有自己的state、mutation、action、getters和子模块,以便提高应用程序的可维护性。

使用方法示例:

const store = new Vuex.Store({
  modules: {
    cart: {
      state: {
        items: []
      },
      mutations: {
        pushProductToCart (state, payload) {
          state.items.push({
            id: payload.id,
            quantity: 1
          })
        }
      },
      actions: {
        addProductToCart ({ state, commit }, product) {
          const cartItem = state.items.find(item => item.id === product.id)
          if (!cartItem) {
            commit('pushProductToCart', product)
          }
        }
      },
      getters: {
        cartItems: state => {
          return state.items
        }
      }
    }
  }
})

这个代码创建了一个包含cart模块的Vuex store对象,其中cart模块包含state、mutations、actions和getters四个属性,用于管理购物车数据。在addProductToCart action中,使用state.items和commit方法来修改cart模块中的数据。在cartItems getter中,使用state.items来计算购物车中的商品数量和总价。





Vuex是Vue.js的状态管理库,它提供了一种集中式存储管理应用程序中所有组件的状态,并将其分离到一个可预测的状态容器中。Vuex包括五个核心属性:

1:State:存放应用程序的状态(数据),所有组件共享。它是Vue实例的data属性的替代品,但是通过它存储和管理的状态,可以在整个应用程序中实现全局共享,即不同的组件可以通过定义的getter和setter访问同一状态数据。


2:Getter:用于获取State中的状态,主要用于对state进行逻辑上的组合和应用,类似于Vue组件中的计算属性。


3:Mutation:用于修改State中的状态,只能同步执行。Mutation必须是同步函数,因为它们不能处理异步行为,异步行为应该放在Action中处理。


4:Action:可以包含任意异步操作(例如从服务器获取数据),可以用Mutation通过提交(commit)来修改State。


5:Module:用于将State、Getter、Mutation、Action模块化,便于组件化和模块化开发。


下面是一个简单的Vuex使用方法的示例:

// 引入Vue和Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 创建一个Store
const store = new Vuex.Store({
  // 定义State
  state: {
    count: 0
  },
  // 定义Mutation
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  },
  // 定义Getter
  getters: {
    evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
  },
  // 定义Action
  actions: {
    incrementIfOdd ({ commit, state }) {
      if ((state.count + 1) % 2 === 0) {
        commit('increment')
      }
    }
  }
})
new Vue({
  el: '#app',
  store,
  template: `
    <div>
      <p>Count: {{ count }}</p>
      <p>Even or Odd? {{ evenOrOdd }}</p>
      <button @click="increment">Increment</button>
      <button @click="decrement">Decrement</button>
      <button @click="incrementIfOdd">IncrementIfOdd</button>
    </div>
  `,
  computed: {
    count () {
      return this.$store.state.count
    },
    evenOrOdd () {
      return this.$store.getters.evenOrOdd
    }
  },
  methods: {
    increment () {
      this.$store.commit('increment')
    },
    decrement () {
      this.$store.commit('decrement')
    },
    incrementIfOdd () {
      this.$store.dispatch('incrementIfOdd')
    }
  }
})

这个代码创建了一个Vuex Store,并定义了State、Mutation、Getter、Action。然后将Store实例与Vue实例关联。在Vue组件中,使用计算属性(computed)和方法(methods)来访问State、Getter和Action。在方法中,使用commit来提交Mutation,使用dispatch来分发Action。

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/3795.html

分享给朋友:

“vuex的五个属性及使用方法示例(vuex的几个属性及其作用)” 的相关文章

宽带客户收费管理系统--维修版

宽带客户收费管理系统--维修版headerfooter《宽带客户收费管理系统——维修版》是一款适合宽带运营商使用的管理系统。软件主要包括以下功能:1.主要功能包括用户开户、收费录入、工单登记、故障处理;2.自定义套餐及收费功能;3.强大的查询功能和数据备份功能以及严密的用户权限功能;4.界面设计简洁...

一套智能停车场收费管理系统设计方案,拓扑图VISIO格式

大家好,我是薛哥。最近VIP会员群的读者咨询停车场管理系统的规划设计方案,今天分享一个模板素材,主要里面的拓扑图可以编辑的,VISIO格式,建议收藏备用。此套完整的Word方案,VIP会员下载!智能停车场收费管理子系统1、系统概述本次停车场管理系统设计纯车牌识别系统,并可在合适的位置设置中央收费点,...

红帽最新的企业 Linux 发行版具有解决混合云复杂性的新功能

据zdnet网5月1日报道,红帽这家 Linux 和超云领导者今天发布了其最新的旗舰 Linux 发行版 Red Hat Enterprise Linux (RHEL) 9.4,此前上周宣布对已有十年历史的流行 RHEL 7.9 再支持四年。这个领先的企业 Linux 发行版的最新版本引入了许多新功...

基于gitlab的PR操作教程

基于gitlab的PR操作教程注:该教程主要基于git命令行操作,其他图形化工具也可完成以下所有操作步骤,顺手即可。推荐工具:Source Tree ,TortoiseGit参考:gitflow一 . 基于分支的PR操作1. 本地切换到master分支1. 拉取最新代码2. 基于master创建ho...

壹啦罐罐 Android 手机里的 Xposed 都装了啥

这是少数派推出的系列专题,叫做「我的手机里都装了啥」。这个系列将邀请到不同的玩家,从他们各自的角度介绍手机中最爱的或是日常使用最频繁的 App。文章将以「每周一篇」的频率更新,内容范围会包括 iOS、Android 在内的各种平台和 App。本期继续歪楼,由少数派撰稿作者@壹啦罐罐介绍他正在使用的...

高效使用 Vim 编辑器的 10 个技巧

在 Reverb,我们使用 MacVim 来标准化开发环境,使配对更容易,并提高效率。当我开始使用 Reverb 时,我以前从未使用过 Vim。我花了几个星期才开始感到舒服,但如果没有这样的提示,可能需要几个月的时间。这里有十个技巧可以帮助你在学习使用 Vim 时提高效率。1. 通过提高按键重复率来...