一、简介
1.1 vuex是什么
1.2 什么时候使用vuex
二、求和案例_纯vue版
2.1 实现效果
2.2 具体实现
app.vue Count.vue 或者:
三、vuex工作原理图
四、求和案例_vuex版
4.1 搭建vuex环境
src/App.vue:
1、下载 Vuex:npm i vuex
2、创建src/store/index.js:
创建src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {}
const mutations = {}
const state = {}
export default new Vuex.Store({
actions,
mutations,
state
})
3、在src/main.js中创建 vm 时传入store配置项:
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store'
Vue.config.productionTip = false
Vue.use(Vuex)
new Vue({
el:"#app",
render: h => h(App),
store
})
4.2 使用vuex编写
src/components/Count.vue:
<template>
<div>
<h1>当前求和为:{{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
increment(){
this.$store.commit('ADD',this.n)
},
decrement(){
this.$store.commit('SUBTRACT',this.n)
},
incrementOdd(){
this.$store.dispatch('addOdd',this.n)
},
incrementWait(){
this.$store.dispatch('addWait',this.n)
},
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
addOdd(context,value){
console.log("actions中的addOdd被调用了")
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
console.log("actions中的addWait被调用了")
setTimeout(()=>{
context.commit('ADD',value)
},500)
},
}
const mutations = {
ADD(state,value){
state.sum += value
},
SUBTRACT(state,value){
state.sum -= value
}
}
const state = {
sum:0
}
export default new Vuex.Store({
actions,
mutations,
state
})
4.3 总结
Vuex的基本使用:
1、初始化数据state,配置actions、mutations,操作文件store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
jia(context,value){
context.commit('JIA',value)
},
}
const mutations = {
JIA(state,value){
state.sum += value
}
}
const state = {
sum:0
}
export default new Vuex.Store({
actions,
mutations,
state,
})
2、 组件中读取vuex中的数据:$store.state.sum
3、 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据) 或 $store.commit('mutations中的方法名',数据)
- 备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit
五、getters配置项
5.1 使用
src/Count.vue:
<template>
<div>
<h1>当前求和为:{{$store.state.sum}}</h1>
<h3>当前求和的10倍为:{{$store.getters.bigSum}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
increment(){
this.$store.commit('ADD',this.n)
},
decrement(){
this.$store.commit('SUBTRACT',this.n)
},
incrementOdd(){
this.$store.dispatch('addOdd',this.n)
},
incrementWait(){
this.$store.dispatch('addWait',this.n)
},
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
addOdd(context,value){
console.log("actions中的addOdd被调用了")
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
console.log("actions中的addWait被调用了")
setTimeout(()=>{
context.commit('ADD',value)
},500)
},
}
const mutations = {
ADD(state,value){
state.sum += value
},
SUBTRACT(state,value){
state.sum -= value
}
}
const state = {
sum:0
}
const getters = {
bigSum(){
return state.sum * 10
}
}
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
5.2 总结
getters配置项的使用:
1、概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
2、在store.js中追加getters配置
const getters = {
bigSum(state){
return state.sum * 10
}
}
export default new Vuex.Store({
...
getters
})
3、组件中读取数据:$store.getters.bigSum
六、四个map方法的使用
6.1 mapState与mapGetters
src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
addOdd(context,value){
console.log("actions中的addOdd被调用了")
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
console.log("actions中的addWait被调用了")
setTimeout(()=>{
context.commit('ADD',value)
},500)
},
}
const mutations = {
ADD(state,value){
state.sum += value
},
SUBTRACT(state,value){
state.sum -= value
}
}
const state = {
sum:0,
name:'JOJO',
school:'尚硅谷',
}
const getters = {
bigSum(){
return state.sum * 10
}
}
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
src/components/Count.vue:
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h3>当前求和的10倍为:{{bigSum}}</h3>
<h3>我是{{name}},我在{{school}}学习</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
increment(){
this.$store.commit('ADD',this.n)
},
decrement(){
this.$store.commit('SUBTRACT',this.n)
},
incrementOdd(){
this.$store.dispatch('addOdd',this.n)
},
incrementWait(){
this.$store.dispatch('addWait',this.n)
},
},
computed:{
...mapState({sum:'sum',school:'school',name:'name'}),
...mapGetters(['bigSum'])
}
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
效果:
6.2 总结
总结:
1、mapState方法:用于帮助我们映射state中的数据
computed: {
...mapState({sum:'sum',school:'school',subject:'subject'}),
...mapState(['sum','school','subject']),
},
2、mapGetters方法:用于帮助我们映射getters中的数据
computed: {
...mapGetters({bigSum:'bigSum'}),
...mapGetters(['bigSum'])
},
6.3 mapActions与mapMutations
src/components/Count.vue:
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h3>当前求和的10倍为:{{bigSum}}</h3>
<h3>我是{{name}},我在{{school}}学习</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
...mapMutations({increment:'ADD',decrement:'SUBTRACT'}),
...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'})
},
computed:{
...mapState({sum:'sum',school:'school',name:'name'}),
...mapGetters(['bigSum'])
}
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
6.4 总结
1、mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数
methods:{
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
...mapActions(['jiaOdd','jiaWait'])
}
2、mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数
methods:{
...mapMutations({increment:'JIA',decrement:'JIAN'}),
...mapMutations(['JIA','JIAN']),
}
- 备注:mapActions与mapMutations使用时,若需要传递参数,则需要在模板中绑定事件时传递好参数,否则参数是事件对象
七、多组件共享数据
src/App.vue:
<template>
<div class="container">
<Count/>
<hr/>
<Person/>
</div>
</template>
<script>
import Count from './components/Count'
import Person from './components/Person'
export default {
name:'App',
components:{Count,Person}
}
</script>
src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
addOdd(context,value){
console.log("actions中的addOdd被调用了")
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
console.log("actions中的addWait被调用了")
setTimeout(()=>{
context.commit('ADD',value)
},500)
},
}
const mutations = {
ADD(state,value){
state.sum += value
},
SUBTRACT(state,value){
state.sum -= value
},
ADD_PERSON(state,value){
console.log('mutations中的ADD_PERSON被调用了')
state.personList.unshift(value)
}
}
const state = {
sum:0,
name:'JOJO',
school:'尚硅谷',
personList:[
{id:'001',name:'JOJO'}
]
}
const getters = {
bigSum(){
return state.sum * 10
}
}
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
src/components/Count.vue:
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h3>当前求和的10倍为:{{bigSum}}</h3>
<h3>我是{{name}},我在{{school}}学习</h3>
<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
...mapMutations({increment:'ADD',decrement:'SUBTRACT'}),
...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'})
},
computed:{
...mapState(['sum','school','name','personList']),,
...mapGetters(['bigSum'])
}
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
src/components/Person.vue:
<template>
<div>
<h1>人员列表</h1>
<h3 style="color:red">Count组件求和为:{{sum}}</h3>
<input type="text" placeholder="请输入名字" v-model="name">
<button @click="add">添加</button>
<ul>
<li v-for="p in personList" :key="p.id">{{p.name}}</li>
</ul>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'Person',
data() {
return {
name:''
}
},
computed:{
personList(){
return this.$store.state.personList
},
sum(){
return this.$store.state.sum
}
},
methods: {
add(){
const personObj = {id:nanoid(),name:this.name}
this.$store.commit('ADD_PERSON',personObj)
this.name = ''
}
}
}
</script>
效果:
八、模块化+命名空间
src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
Vue.use(Vuex)
export default new Vuex.Store({
modules:{
countAbout:countOptions,
personAbout:personOptions,
}
})
src/store/count.js:
export default{
namespaced:true,
actions:{
addOdd(context,value){
console.log("actions中的addOdd被调用了")
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
console.log("actions中的addWait被调用了")
setTimeout(()=>{
context.commit('ADD',value)
},500)
}
},
mutations:{
ADD(state,value){
state.sum += value
},
SUBTRACT(state,value){
state.sum -= value
}
},
state:{
sum:0,
name:'JOJO',
school:'尚硅谷',
},
getters:{
bigSum(state){
return state.sum * 10
}
}
}
src/store/person.js:
import axios from "axios"
import { nanoid } from "nanoid"
export default{
namespaced:true,
actions:{
addPersonWang(context,value){
if(value.name.indexOf('王') === 0){
context.commit('ADD_PERSON',value)
}else{
alert('添加的人必须姓王!')
}
},
addPersonServer(context){
axios.get('http://api.uixsj.cn/hitokoto/get?type=social').then(
response => {
context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
},
error => {
alert(error.message)
}
)
}
},
mutations:{
ADD_PERSON(state,value){
console.log('mutations中的ADD_PERSON被调用了')
state.personList.unshift(value)
}
},
state:{
personList:[
{id:'001',name:'JOJO'}
]
},
getters:{
firstPersonName(state){
return state.personList[0].name
}
}
}
src/components/Count.vue:
<template>
<div>
<h1>当前求和为:{{sum}}</h1>
<h3>当前求和的10倍为:{{bigSum}}</h3>
<h3>我是{{name}},我在{{school}}学习</h3>
<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1,
}
},
methods: {
...mapMutations('countAbout',{increment:'ADD',decrement:'SUBTRACT'}),
...mapActions('countAbout',{incrementOdd:'addOdd',incrementWait:'addWait'})
},
computed:{
...mapState('countAbout',['sum','school','name']),
...mapGetters('countAbout',['bigSum']),
...mapState('personAbout',['personList'])
}
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
src/components/Person.vue:
<template>
<div>
<h1>人员列表</h1>
<h3 style="color:red">Count组件求和为:{{sum}}</h3>
<h3>列表中第一个人的名字是:{{firstPersonName}}</h3>
<input type="text" placeholder="请输入名字" v-model="name">
<button @click="add">添加</button>
<button @click="addWang">添加一个姓王的人</button>
<button @click="addPerson">随机添加一个人</button>
<ul>
<li v-for="p in personList" :key="p.id">{{p.name}}</li>
</ul>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'Person',
data() {
return {
name:''
}
},
computed:{
personList(){
return this.$store.state.personAbout.personList
},
sum(){
return this.$store.state.countAbout.sum
},
firstPersonName(){
return this.$store.getters['personAbout/firstPersonName']
}
},
methods: {
add(){
const personObj = {id:nanoid(),name:this.name}
this.$store.commit('personAbout/ADD_PERSON',personObj)
this.name = ''
},
addWang(){
const personObj = {id:nanoid(),name:this.name}
this.$store.dispatch('personAbout/addPersonWang',personObj)
this.name = ''
},
addPerson(){
this.$store.dispatch('personAbout/addPersonServer')
}
},
}
</script>
效果:
总结: 模块化+命名空间:
1、目的:让代码更好维护,让多种数据分类更加明确
2、修改store.js:
const countAbout = {
namespaced:true,
state:{x:1},
mutations: { ... },
actions: { ... },
getters: {
bigSum(state){
return state.sum * 10
}
}
}
const personAbout = {
namespaced:true,
state:{ ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
countAbout,
personAbout
}
})
3、开启命名空间后,组件中读取state数据:
this.$store.state.personAbout.list
...mapState('countAbout',['sum','school','subject']),
4、开启命名空间后,组件中读取getters数据:
this.$store.getters['personAbout/firstPersonName']
...mapGetters('countAbout',['bigSum'])
5、开启命名空间后,组件中调用dispatch:
this.$store.dispatch('personAbout/addPersonWang',person)
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
6、开启命名空间后,组件中调用commit:
this.$store.commit('personAbout/ADD_PERSON',person)
...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
|