Vuex
采用集中式存储所有组件的数据状态,并且组件状态和后台数据是响应的
Vuex核心概念
-
state:驱动应用的数据源
-
getters:为组件提供经过处理的数据源
-
mutations:用来更改 state 的唯一标准方式
-
actions:组件通过调用 actions 来提交 mutation
-
modules:每个 module 都有自己的 state、getters、mutations、actions 实现大型应用中业务模块数据的分支
state
-
存数据,也可以获取
-
组件中通过
computed
属性来获取数据 -
return this.$store.state.products;
store.js
state: {// 存数据 products: [ { name: "马云", price: 200 }, { name: "马化腾", price: 140 }, { name: "马冬梅", price: 20 }, { name: "马蓉", price: 10 } ] }
app.vue
computed: { products() { return this.$store.state.products; } }
<li v-for="(item,i) in products" :key="i"> name: <span>{{item.name}}</span> 有这么多钱: <span>{{item.price}}</span> </li>
getters
-
获取数据,在这个函数里更改原数据并
return
出去 -
组件中通过
-
return this.$store.getters.saleProducts;
store.js
getters: {// 获取数据 saleProducts: state => { return state.products.map(item => { return { name: '**' + item.name + '**', price: parseInt(item.price / 1.5) } }) } },
app.vue
computed: { saleProducts() { return this.$store.getters.saleProducts; } }
mutations
-
事件注册,数据里的一切逻辑实现都写在这里
-
组件中通过
methods
属性来执行mutations
里的函数 -
this.$store.commit("reducePrice");
-
这个属性不适合处理异步事件,因为在调试工具里不会等异步执行完就出结果
store.js
mutations: {// 事件注册 reducePrice: (state) => { state.products.forEach(item => { item.price -= 1 }) }
app.vue
methods: { reducePrice: function() { // mutations this.$store.commit("reducePrice"); } }
<button @click="reducePrice">商品降价</button>
-
事件注册 处理异步事件 可以传参
-
组件中通过
methods
属性来执行actions
里的函数 -
this.$store.dispatch('reducePrice', amount)
-
这个属性用来处理异步
store.js
actions: {// 事件注册 处理异步事件 可以传参 reducePrice: (context,playload) => { setTimeout(() => { context.commit('reducePrice', playload) }, 2000); } }
app.vue
methods: { reducePrice: function(amount) { // actions this.$store.dispatch('reducePrice', amount) } }
<button @click="reducePrice(4)">商品降价</button>