Vuex的基本使用

一、基本用法

1、使用

  1. 安装vuex依赖包
npm i vuex - save
  1. 导入vuex包 [ store / index.js ]
import Vue from 'vue'
import Vuex from 'vuex' // 1、导入vuex包
Vue.use(Vuex)          //  1、导入vuex包

// 2、创建 store 对象
export default new Vuex.Store({
 state: { },   // state提供唯一的公共数据源,所有共享的数据都要统一放到state中进行存储
 mutations: {}, // mutation 用于变更 store 中的数据
 actions: {},
 modules: {}
})

  1. 将store对象挂载到vue实例中 [ main.js入口文件 ]
import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
 store, // 将store对象挂载到vue实例中
 render: h => h(App)
}).$mount('#app')

  • store / index.js
import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
  state: {
    count: 0
  },
  // 突变
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

2、State

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

  • 组件访问state中数据的方式:
    (1)方法
    this.$store.state.全局数据名
<template>
  <div>
      //template中 this 可以省略 直接写
      <h3>最新count值:{{$store.state.count}}</h3>
  </div>
</template>

<script>
export default {
  data () {
    return {}
  },
  methods: {}
}
</script>

(2)方法2

<template>
  <div>
      <h3>最新count值:{{count}}</h3>
  </div>
</template>

<script>
// 1、从vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
export default {
  // 通过导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性
  computed: {
  // 2、将全局数据,映射为当前组件的计算属性
    ...mapState(['count'])
  },
  data () {
    return {}
  }
}
</script>

2、 Mutations 突变

mutations 用于变更store中的数据。
(1)只能通过 mutations 变更 store 中的数据,不可以直接操作 store 中的数据。
(2)通过mutations操作虽然稍微繁琐些,但是可以集中监控所有数据的变化。

问题: 点击按钮对count值加1:
<template>
  <div>
      <h3>最新count值:{{$store.state.count}}</h3>
      <button @click="btnAdd">btnAdd +1</button>
  </div>
</template>

<script>
export default {
  methods: {
    btnAdd () {
      this.$store.state.count++
    }
  }
}
</script>

btnAdd()方法这样直接对store中的数据操作是不允许的,虽然可实现功能,但是不推荐,而且后期数据多的话也不方便查找。

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  // 1、定义 mutation
  mutations: {
    add (state) {
      // 2、变更状态
      state.count++
    },
    // 带参数的突变
    addN (state, item) {
      state.count += item
    },
  }
})

  • 触发 mutations 的方式:
    方式1: this.store.commit(‘ ’)
<template>
  <div>
      <h3>最新count值:{{$store.state.count}}</h3>
      <button @click="handle1">+1</button>
      <button @click="handle2">+3</button>
  </div>
</template>

<script>
export default {
  methods: {
    handle1 () {
      this.$store.commit('add')
    },
    handle2 () {
      this.$store.commit('addN', 3)
    }
  }
}
</script>

方式2:

<template>
  <div>
      <h3>最新count值:{{$store.state.count}}</h3>
      <button @click="handle1">+1</button>
      <button @click="handle2">+3</button>

  </div>
</template>

<script>
// 1、按需导入 mapMutations 函数
import { mapMutations } from 'vuex' 
export default {
  data () {
    return {}
  },
  methods: {
    // 2、通过导入的 mapMutations 函数,将需要的 mutations 函数 映射为当前组件的 methods 方法
    ...mapMutations(['add', 'addN']),
    handle1 () {
      this.add()
    },
    handle2 () {
      this.addN(3)
    }
  }
}
</script>

问题: 点击实现隔一秒加1
  • store / index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      setTimeout(() => {
        state.count++
      }, 1000)
    }
  },
})

  • Addition. vue
<template>
  <div>
      <h3>最新count值:{{$store.state.count}}</h3>
      <button @click="handle">延时+1</button>
 
  </div>
</template>
 
<script>
import { mapMutations } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    ...mapMutations(['add']),
    handle () {
      this.add()
    }
  }
}
</script>

点击延时+1按钮,会发现 count 的值还是初始值,未发生变化:

点击延时+1按钮,会发现 count 的值还是初始值,未发生变化。所以 不要在 mutations 突变中执行异步操作
所以 不要在 mutations 突变中执行异步操作 (Actions

3、Actions

如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发 Mutation 的方式间接变更数据。
在这里插入图片描述
问题:隔一秒,加/减1、加/减N

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      state.count++
    },
    addN (state, item) {
      state.count += item
    },
    sub (state) {
      state.count--
    },
    subN (state, item) {
      state.count -= item
    }
  },
  actions: {
    // context new出来的 store 实例对象
    addAsync (context) {
      setTimeout(() => {
        context.commit('add') 
      }, 1000)
    },
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    },
    subAsync (context) {
      setTimeout(() => {
        context.commit('sub') 
      }, 1000)
    },
    subNAsync (context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      })
    }
  }
})

注意:在action中不能直接修改state中的数据 必须通过context.commit(’’) 触发某个 mutation才行 只有mutations才有权利修改 state中的数据

触发 actions 的两方式:

方式1:

<template>
  <div>
      <h3>最新count值:{{$store.state.count}}</h3>
      <button @click="handle1">异步count+1</button>
      <button @click="handle2">异步count+3</button>
  </div>
</template>

<script>
export default {
  methods: {
    handle1 () {
    // dispatch函数 专门用来触发actions
      this.$store.dispatch('addAsync')
    },
    handle2 () {
      this.$store.dispatch('addNAsync', 3)
    }
  }
}
</script>

方式2:

<template>
  <div>
      <h3>最新count值:{{count}}</h3>
      <button @click="subAsync">异步-1</button>
      <button @click="subNAsync(3)">异步-3</button>
  </div>
</template>

<script>
// 1、导入mutations
import { mapState, mapActions } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    // 2、将 mapActions中所需函数,映射为当前组件的 methods方法 可以直接在template中调用
    ...mapActions(['subAsync', 'subNAsync'])
    // handle1 () {
    //   this.subAsync() 
    // },
    // handle2 () {
    //   this.subNAsync(3)
    // }
  },
  computed: {
    ...mapState(['count']) // 获取 state 的第二种方式
  }
}
</script>

4、getters

getters用于对store中的数据进行加工处理形成新的数据。

  • getter可以对store中已有的数据进行加工处理,之后形成新的数据,类似于vue的计算属性。
  • store中的数据发证变化,getters的数据也会发生变化。

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    sub (state) {
      state.count--
    },
    subN (state, item) {
      state.count -= item
    }
  },
  actions: {
    subAsync (context) {
      setTimeout(() => {
        context.commit('sub') // 在action中不能直接修改state中的数据 必须通过context.commit('') 触发某个 mutation才行 只有mutations才有权利修改 state中的数据
      }, 1000)
    },
    subNAsync (context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      })
    }
  },
  getters: {
    showNum (state) {
      return '当前最新的数量:【' + state.count + '】'
    }
  }
})


使用getters的方式:
方式1:

<template>
  <div>
      <h3>{{$store.getters.showNum}}</h3>
      <button @click="btnAdd">btnAdd +1</button>
      <button @click="handle1">+1</button>
      <button @click="handle2">+3</button>
      <button @click="handle3">异步count+1</button>
      <button @click="handle4">异步count+3</button>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    btnAdd () {
      this.$store.state.count++
    },
    ...mapMutations(['add', 'addN']),
    handle () {
      this.add()
    },
    handle1 () {
      this.$store.commit('add')
    },
    handle2 () {
      this.$store.commit('addN', 3)
    },
    handle3 () {
      this.$store.dispatch('addAsync')
    },
    handle4 () {
      this.$store.dispatch('addNAsync', 3)
    }
  }
}
</script>

在这里插入图片描述

方式2:


<template>
  <div>
      <h3>最新count值:{{count}}</h3>
      <p>showNum</p>
      <h3>{{showNum}}</h3>
      <button @click="sub">-1</button>
      <button @click="subN(3)">-3</button>
      <button @click="subAsync">异步-1</button>
      <button @click="subNAsync(5)">异步-5</button>
  </div>
</template>

<script>
// 1、导入
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  data () {
    return {}
  },
  methods: {
    // 2、将 mutations中所需函数,映射为当前组件的 methods方法
    ...mapMutations(['sub', 'subN']),
    ...mapActions(['subAsync', 'subNAsync'])
  },
  computed: {
    ...mapState(['count']), 
    ...mapGetters(['showNum']) // 将 showNum 映射为当前组件的计算属性
  }
}
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值