vuex状态管理

vuex

    主要应用于vue.js中管理数据状态的一个库

    通过创建一个集中的数据存储,供程序中所有组件访问

vuex核心概念:state、getters、mutations、actions、module


一、vuex 安装引入

1、安装vuex

npm install vuex --save

2、vue项目中导入vuex

在src目录下新建store/store.js文件,在该js文件中引入vuex

//1.引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
//2.使用vuex
Vue.use(Vuex)
//3.创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
  //state存放公共基础数据
  state:{
  
  },
  //对数据的处理
  getters:{
  
  }
//4.向外暴露store数据仓库,这样其他vue组件才能使用store内的数据
export default store

3、将store对象挂载到vue实例中

在src/main.js下

//1.引入store
import store from './store/store'

new Vue({
  //2.挂载store对象
  store:store,
})

4、在vue组件中使用store.js内的数据

    使用computed计算属性,通过调用this.$store.state.属性名,获取到需要的数据。

html:
  <div>
    <h2>product-list-one:</h2>
    <ul>
    //2.使用数据
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
js:
  computed:{
  //1.获取store.js中的数据
    products(){
      return this.$store.state.products
    },
  }

二、state:{}

    state 提供唯一的公告数据源,所有共享的数据都要统一放到 store 的 state 中进行存储。我们需要保存的数据就保存在这里,可以在组件页面通过 this.$store.state.属性名来获取我们定义的数据。

组件访问store中数据的两种方式:

1、this.$store.state.属性名

store.js中定义数据

//1.引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
//2.使用vuex
Vue.use(Vuex)
//3.创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
  //state存放公共基础数据
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  //对数据的处理
  getters:{
  }
//4.向外暴露store数据仓库,这样其他vue组件才能使用store内的数据
export default store

vue组件中使用store.js数据

html:
  <div>
    <h2>product-list-one:</h2>
    <ul>
    //2.使用数据
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
js:
  computed:{
  //1.获取store.js中的数据
    products(){
      return this.$store.state.products
    },
  }

2、将store.js数据,映射为当前组件的计算属性

在store.js中定义属性msg

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state:{
    msg:'映射为计算属性'
  },
})
export default store

在组件中映射属性为计算属性

<template>
  <div>
  //3.使用store中定义的msg属性
    <span>{{msg}}</span>
  </div>
</template>

<script>
// 1.从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
  // 2.将全局数据,映射为当前组件的计算属性
    ...mapState(['msg'])// 用...展开运算符把 msg展开在资源属性里
  }
}
</script>

三、getters:{}

    Getter 用于对 Store 中的数据进行加工处理形成新的数据。不会修改 state 里的源数据,只起到一个包装器的作用,将 state 里的数据变一种形式然后返回出来。

① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。

② Store 中数据发生变化,Getter 包装出来的数据也会跟着变化。

1、定义getters:

const store = new Vuex.Store({
  getters: {
  
  }
})

2、getters的两种使用方式(和state的两种使用方式相同):

① this.$store.getters.方法名

在store.js中定义方法

const store = new Vuex.Store({
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  }
})

在组件计算属性获取到使用handleProducts()方法

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
    //2.通过计算属性使用数据
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "ProductListTwo",
  computed:{
    products(){
      return this.$store.state.products
    },
    handleProducts(){
    //1.获取store.js中定义的数据处理方法
      return this.$store.getters.handleProducts
    }
  }
}
</script>

或者也可以直接在html中使用

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
    //在{{}}中直接通过this.$store.getters.handleProducts获取到数据
      <li v-for="product in this.$store.getters.handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

② 在组件中映射属性为计算属性

在store.js中定义方法handleProducts()

const store = new Vuex.Store({
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  }
})

在组件中使用handleProducts()方法

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

<script>
// 1.从 vuex 中按需导入 mapState 函数
import  {mapState, mapGetters} from 'vuex'
export default {
  name: "ProductListOne",
  // 2.将全局数据,映射为当前组件的计算属性
  computed:{
    ...mapGetters(['handleProducts'])// 用...展开运算符把 handleProducts展开在资源属性里
  }
}
</script>

四、Mutations

    Mutations 用于变更 Store 中的数据。严格模式下(strict:true),只有 mutation 里的函数才有权利去修改 state 中的数据。mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。但是,mutation只允许同步函数,不能写异步的代码。

①严格模式下(strict:true),只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。

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

1、定义mutations:{}

const store = new Vuex.Store({
  mutations: {
  
    }
  }
})

2、mutations的两种触发方式:(与state、getters的两种触发方式一样)

① this.$store.commit('事件名')

在store.js中定义事件declinePrice

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  strict:true,//严格模式下,vuex里的数据组件只能通过commit触发store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
  },
  mutations:{
  //1、定义事件declinePrice
    declinePrice: (state)=>{
      state.products.forEach((product)=>{
        product.price--
      })
    }
  }
})

export default store

在vue组件中调用commit改变store中的数据

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
export default {
  name: "ProductListTwo",
  computed:{
    products(){
      return this.$store.state.products
    },
  },
  methods:{
    declinePrice: function (){
    //通过commit调用函数,改变store的数据
      this.$store.commit('declinePrice')
    }
  }
}
</script>

<style scoped>

</style>

*mutations传递参数

在组件中的代码:

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

打开 store/index.js 文件,增加一个 addN:

mutations: {
//形参step接收组件传的参数3
    addN (state, step) {
      state.count += step
    }
}

②从 vuex 中按需导入 mapMutations 函数
在store.js文件中定义declinePrice函数

const store = new Vuex.Store({
  strict:true,//严格模式下,vuex里的数据组件只能通过commit触发store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
  },
  mutations:{
    declinePrice: (state)=>{
      state.products.forEach((product)=>{
        product.price--
      })
    }
  }
})

在组件中使用:

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
//1.将指定的 mutations 函数,映射为当前组件的 methods 函数
import {mapGetters,mapMutations} from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
    products(){
      return this.$store.state.products
    },
  },
  methods:{
    ...mapMutations(['declinePrice'])用...展开运算符把declinePrice展开在methods里
  }
}

五、Actions

Actions类似于mutations,不同在于:

  • Actions提交的是mutations,而不是直接变更状态
  • Actions可以包含任意异步操作

1、定义actions

// 定义 Action
const store = new Vuex.Store({
 actions: {

   }
 }
})

2、Actions的两种触发方式:

① this.$store.dispatch('方法名')

例子:目的-设置一个定时器,三秒后number自减

在store.js中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  strict:true,//严格模式下,vuex里的数据组件只能通过commit触发store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
    msg:'映射为计算属性'
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  },
  mutations:{
    declinePrice: (state)=>{
        state.products.forEach((product)=>{
          product.price--
        })

    }
  },
  actions:{
  //1.定义一个属性declinePrice,
  //context相当与this.$store
    declinePrice:(context)=>{
    //2.定时器三秒后触发mutations里面的declinePrice属性
      setTimeout(()=>{
        context.commit('declinePrice')
      },3000)
    }
  }
})

export default store

在vue组件中

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
// 1.从 vuex 中按需导入 mapState 函数
import {mapGetters,mapMutations} from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
    products(){
      return this.$store.state.products
    },
    // 2.将全局数据,映射为当前组件的计算属性
    ...mapGetters(['handleProducts'])
  },
  methods:{
  //3.onclick事件,通过this.$store.dispatch('declinePrice')去触发store.js中的actions
     declinePrice: function(){
       this.$store.dispatch('declinePrice')
     }
  }
}
</script>

<style scoped>

</style>

②从 vuex 中按需导入 mapActions 函数

使用方法和state、getters、mutations相同

六、module

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

待续......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,104评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,816评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,697评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,836评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,851评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,441评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,992评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,899评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,457评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,529评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,664评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,346评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,025评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,511评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,611评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,081评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,675评论 2 359

推荐阅读更多精彩内容