Vue基础21之Vuex第二节

Vuex

多组件共享数据

在这里插入图片描述

Calculation.vue

<template>
<div>
  <h1>当前求和为:{{sum}}</h1>
  <h2>当前求和数放大10倍后为:{{bigSum}}</h2>
  <h3>我在{{school}}学习{{subject}}</h3>
  <h3 style="color: red;">person组件的总人数为:{{personList.length}}</h3>
  <div class="event">
<!--    v-model.number强制转换为数字-->
    <select  class="same" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button class="same" @click="increment(n)">+</button>
    <button class="same" @click="decrement(n)">-</button>
    <button class="same" @click="incrementOdd(n)">当前和为奇数再加</button>
    <button class="same" @click="incrementWait(n)">等一等再加</button>
  </div>
</div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
    export default {
      name: "Calculation",
      data(){
          return{
            n:1, //用户选择的数字
          }
      },
      methods:{
        ...mapMutations({increment:"Addmore",decrement:"Deduce"}),
        ...mapActions({incrementOdd:"addOdd",incrementWait:"addWait"})
      },
      computed:{
        //借助mapState生成计算属性,从state中读取数据(对象写法)
        // ...mapState({he:"sum",xuexiao:"school",xueke:"subject"}),

        //借助mapState生成计算属性,从state中读取数据(数组写法)
        ...mapState(["sum","school","subject","personList"]),

        //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
        // ...mapGetters({bigSum:'bigSum'})
        // 借助mapGetters生成计算属性,从getters中读取数据(数组写法)
        ...mapGetters(["bigSum"])
      },
      mounted() {
        // const x=mapState({he:"sum",xuexiao:"school",xueke:"subject"})
        const x=mapState(["sum","school","subject"])
        console.log(x)
      }
    }
</script>

<style scoped>
.event{
  display: flex;
  justify-content: space-between;
  width: 300px;
}
</style>

Persons.vue

<template>
  <div>
    <h1>人员列表</h1>
    <h3 style="color: red;">calculation组件求和为:{{sum}}</h3>
    <input type="text" v-model="name">&nbsp;<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: "Persons",
        data(){
          return{
            name:""
          }
        },
        computed:{
          personList(){
            return this.$store.state.personList
          },
          sum(){
            return this.$store.state.sum
          }
        },
        methods:{
          addPerson(){
            var personObj={id:nanoid(),name:this.name}
            this.$store.commit("AddPerson",personObj)
            this.name=""
          }
        }
    }
</script>

<style scoped>

</style>

src/store/index.js

//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用vuex插件
Vue.use(Vuex)

//准备actions——用于响应组件中的动作
const actions={
    addOdd(context,value){
        if(context.state.sum%2){
            console.log("actions中的addOdd被调用了")
            context.commit("Addmore",value)
        }
    },
    addWait(context,value){
        setTimeout(()=>{
            console.log("actions中的addWait被调用了")
            context.commit("Addmore",value)
        },500)
    }
}
//准备mutations——用于操作数组(state)
const mutations={
    Addmore(state,value){
        console.log("mutations中的Addmore被调用了")
        state.sum+=value
    },
    Deduce(state,value){
        console.log("mutations中的Deduce被调用了")
        state.sum-=value
    },
    AddPerson(state,value){
        state.personList.unshift(value)
    }
}
//准备state——用于存储数组
const state={
    sum:0,
    school:"幸福大学",
    subject:"计算机",
    personList:[
        {id:"001",name:"张三"}
    ]
}

//准备getters——用于将state中的数据进行加工
const getters={
    bigSum(state){
        return state.sum*10
    }
}

//创建并暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

请添加图片描述

vuex模块化+namespace

在这里插入图片描述

模块化

src/store/index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用vuex插件
Vue.use(Vuex)

//求和相关的配置
const countOptions={
    namespaced:true,
    //准备actions——用于响应组件中的动作
    actions:{
        addOdd(context,value){
            if(context.state.sum%2){
                console.log("actions中的addOdd被调用了")
                context.commit("Addmore",value)
            }
        },
        addWait(context,value){
            setTimeout(()=>{
                console.log("actions中的addWait被调用了")
                context.commit("Addmore",value)
            },500)
        }
    },
    //准备mutations——用于操作数组(state)
    mutations:{
        Addmore(state,value){
            console.log("mutations中的Addmore被调用了")
            state.sum+=value
        },
        Deduce(state,value){
            console.log("mutations中的Deduce被调用了")
            state.sum-=value
        },
    },
    //准备state——用于存储数组
    state:{
        sum:0,
        school:"幸福大学",
        subject:"计算机",
    },
    //准备getters——用于将state中的数据进行加工
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}

//人员相关的配置
const personOptions={
    namespaced:true,
    actions:{
        addPersonWang(context,value){
            if(value.name.indexOf("王")==0){
                context.commit("AddPerson",value)
            }else{
                alert("添加的必须是姓王的人!")
            }
        }
    },
    mutations:{
        AddPerson(state,value){
            state.personList.unshift(value)
        }
    },
    state:{
        personList:[
            {id:"001",name:"张三"}
        ]
    },
    getters:{
        firstPersonName(state){
            return state.personList[0].name
        }
    }
}


//创建并暴露store
export default new Vuex.Store({
    modules:{
        countAbout:countOptions,
        personAbout:personOptions
    }
})

Calculation.vue
<template>
<div>
  <h1>当前求和为:{{sum}}</h1>
  <h2>当前求和数放大10倍后为:{{bigSum}}</h2>
  <h3>我在{{school}}学习{{subject}}</h3>
  <h3 style="color: red;">person组件的总人数为:{{personList.length}}</h3>
  <div class="event">
<!--    v-model.number强制转换为数字-->
    <select  class="same" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button class="same" @click="increment(n)">+</button>
    <button class="same" @click="decrement(n)">-</button>
    <button class="same" @click="incrementOdd(n)">当前和为奇数再加</button>
    <button class="same" @click="incrementWait(n)">等一等再加</button>
  </div>
</div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
    export default {
      name: "Calculation",
      data(){
          return{
            n:1, //用户选择的数字
          }
      },
      methods:{
        ...mapMutations('countAbout',{increment:"Addmore",decrement:"Deduce"}),
        ...mapActions('countAbout',{incrementOdd:"addOdd",incrementWait:"addWait"})
      },
      computed:{
        //借助mapState生成计算属性,从state中读取数据(对象写法)
        // ...mapState({he:"sum",xuexiao:"school",xueke:"subject"}),

        //借助mapState生成计算属性,从state中读取数据(数组写法)
        ...mapState('countAbout',["sum","school","subject"]),
        ...mapState('personAbout',["personList"]),

        //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
        // ...mapGetters({bigSum:'bigSum'})
        // 借助mapGetters生成计算属性,从getters中读取数据(数组写法)
        ...mapGetters('countAbout',["bigSum"])
      },
      mounted() {
        console.log(this.$store)
      }
    }
</script>

<style scoped>
.event{
  display: flex;
  justify-content: space-between;
  width: 300px;
}
</style>

Persons.vue
<template>
  <div>
    <h1>人员列表</h1>
    <h3 style="color: red;">calculation组件求和为:{{sum}}</h3>
    <h3>列表中第一个人的名字是:{{firstName}}</h3>
    <input type="text" v-model="name">&nbsp;<button @click="addPerson">添加</button>
    &nbsp;
    <button @click="addWang">添加一个姓王的人</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: "Persons",
        data(){
          return{
            name:""
          }
        },
        computed:{
          personList(){
            return this.$store.state.personAbout.personList
          },
          sum(){
            return this.$store.state.countAbout.sum
          },
          firstName(){
            return this.$store.getters['personAbout/firstPersonName']
          }
        },
        methods:{
          addPerson(){
            var personObj={id:nanoid(),name:this.name}
            this.$store.commit("personAbout/AddPerson",personObj)
            this.name=""
          },
          addWang(){
            var personObj={id:nanoid(),name:this.name}
            this.$store.dispatch("personAbout/addPersonWang",personObj)
            this.name=""
          }
        }
    }
</script>

<style scoped>

</style>

App.vue
<template>
  <div class="bg">
    <Calculation></Calculation>

    <hr>

    <Persons></Persons>
  </div>
</template>

<script>
import Calculation from "@/components/Calculation";
import Persons from "@/components/Persons";
export default {
  name: "App",
  components: {Calculation,Persons},
  mounted() {
    console.log("App",this)
  }
}
</script>



请添加图片描述

发送Ajax请求处理并拆分store

在这里插入图片描述

请求

https://api.uixsj.cn/hitokoto/get?type=social
随机生成语录

src/store/personOptions.js
//人员相关的配置
import axios from "axios";
import {nanoid} from 'nanoid'
export default {
    namespaced:true,
    actions:{
        addPersonWang(context,value){
            if(value.name.indexOf("王")==0){
                context.commit("AddPerson",value)
            }else{
                alert("添加的必须是姓王的人!")
            }
        },
        addPerson(context){
            axios.get("https://api.uixsj.cn/hitokoto/get?type=social").then(
                response=>{
                    context.commit("AddPerson",{id:nanoid(),name:response.data})
                },
                error=>{
                    alert(error.message)
                }
            )
        }

    },
    mutations:{
        AddPerson(state,value){
            state.personList.unshift(value)
        }
    },
    state:{
        personList:[
            {id:"001",name:"张三"}
        ]
    },
    getters:{
        firstPersonName(state){
            return state.personList[0].name
        }
    }
}

src/store/countOptions.js
//求和相关的配置
const countOptions={
    namespaced:true,
    //准备actions——用于响应组件中的动作
    actions:{
        addOdd(context,value){
            if(context.state.sum%2){
                console.log("actions中的addOdd被调用了")
                context.commit("Addmore",value)
            }
        },
        addWait(context,value){
            setTimeout(()=>{
                console.log("actions中的addWait被调用了")
                context.commit("Addmore",value)
            },500)
        }
    },
    //准备mutations——用于操作数组(state)
    mutations:{
        Addmore(state,value){
            console.log("mutations中的Addmore被调用了")
            state.sum+=value
        },
        Deduce(state,value){
            console.log("mutations中的Deduce被调用了")
            state.sum-=value
        },
    },
    //准备state——用于存储数组
    state:{
        sum:0,
        school:"幸福大学",
        subject:"计算机",
    },
    //准备getters——用于将state中的数据进行加工
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}
export default countOptions

main.js
import Vue from 'vue'

import App from './App'
//引入vue-resource插件
import vueresource from 'vue-resource'

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

Vue.config.productionTip = false
//使用vue-resource插件
Vue.use(vueresource)

new Vue({
    el: "#app",
    render: h => h(App),
    store,
    beforeCreate() {
        Vue.prototype.$bus = this
    }
})

src/store/index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用vuex插件
Vue.use(Vuex)

//引入
import countOptions from "@/store/countOptions";
import personOptions from "@/store/personOptions";


//创建并暴露store
export default new Vuex.Store({
    modules:{
        countAbout:countOptions,
        personAbout:personOptions
    }
})

Persons.vue
<template>
  <div>
    <h1>人员列表</h1>
    <h3 style="color: red;">calculation组件求和为:{{sum}}</h3>
    <h3>列表中第一个人的名字是:{{firstName}}</h3>
    <input type="text" v-model="name">&nbsp;<button @click="addPerson">添加</button>
    &nbsp;
    <button @click="addWang">添加一个姓王的人</button> &nbsp;
    <button @click="addPersonServer">添加一个随机的人名</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: "Persons",
        data(){
          return{
            name:""
          }
        },
        computed:{
          personList(){
            return this.$store.state.personAbout.personList
          },
          sum(){
            return this.$store.state.countAbout.sum
          },
          firstName(){
            return this.$store.getters['personAbout/firstPersonName']
          }
        },
        methods:{
          addPerson(){
            var personObj={id:nanoid(),name:this.name}
            this.$store.commit("personAbout/AddPerson",personObj)
            this.name=""
          },
          addWang(){
            var personObj={id:nanoid(),name:this.name}
            this.$store.dispatch("personAbout/addPersonWang",personObj)
            this.name=""
          },
          addPersonServer(){
            this.$store.dispatch("personAbout/addPerson")
          }
        }
    }
</script>

<style scoped>

</style>

Calculation.vue
<template>
<div>
  <h1>当前求和为:{{sum}}</h1>
  <h2>当前求和数放大10倍后为:{{bigSum}}</h2>
  <h3>我在{{school}}学习{{subject}}</h3>
  <h3 style="color: red;">person组件的总人数为:{{personList.length}}</h3>
  <div class="event">
<!--    v-model.number强制转换为数字-->
    <select  class="same" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button class="same" @click="increment(n)">+</button>
    <button class="same" @click="decrement(n)">-</button>
    <button class="same" @click="incrementOdd(n)">当前和为奇数再加</button>
    <button class="same" @click="incrementWait(n)">等一等再加</button>
  </div>
</div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
    export default {
      name: "Calculation",
      data(){
          return{
            n:1, //用户选择的数字
          }
      },
      methods:{
        ...mapMutations('countAbout',{increment:"Addmore",decrement:"Deduce"}),
        ...mapActions('countAbout',{incrementOdd:"addOdd",incrementWait:"addWait"})
      },
      computed:{
        //借助mapState生成计算属性,从state中读取数据(对象写法)
        // ...mapState({he:"sum",xuexiao:"school",xueke:"subject"}),

        //借助mapState生成计算属性,从state中读取数据(数组写法)
        ...mapState('countAbout',["sum","school","subject"]),
        ...mapState('personAbout',["personList"]),

        //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
        // ...mapGetters({bigSum:'bigSum'})
        // 借助mapGetters生成计算属性,从getters中读取数据(数组写法)
        ...mapGetters('countAbout',["bigSum"])
      },
      mounted() {
        console.log(this.$store)
      }
    }
</script>

<style scoped>
.event{
  display: flex;
  justify-content: space-between;
  width: 300px;
}
</style>

App.vue
<template>
  <div class="bg">
    <Calculation></Calculation>
    <hr>
    <Persons></Persons>
  </div>
</template>

<script>
import Calculation from "@/components/Calculation";
import Persons from "@/components/Persons";
export default {
  name: "App",
  components: {Calculation,Persons},
  mounted() {
    console.log("App",this)
  }
}
</script>



请添加图片描述

总结:模块化+命名空间

  1. 目的:让代码更好维护,让多种数据分类更加明确
  2. 修改store.js
const countAbout={
	namespaced:true,//开启命名空间
	state:{x},
	mutations:{...},
	actions:{...},
	getters:{
		bigSum(state){
			return state.sum*10
		}
	}
}

const personAbout={
	namespaced:true,//开启命名空间
	state:{...},
	mutations:{...},
	actions:{...}
}

const store=new Vuex.Store({
	modules:{
		countAbout,
		personAbout
	}
})
  1. 开启命名空间后,组件中读取state数据
//方式一:自己直接读取
this.$store.state.personAbout.list
//方式二:借助mapState读取
...mapState('countAbout',['sum','school','subject']),
  1. 开启命名空间后,组件中读取getters数据
//方式一:自己直接读取
this.$store.getters['personAbout/firstPersonName']
//方式二:借助mapGetters读取
...mapGetters('countAbout',['bigSum']),
  1. 开启命名空间后,组件中调用dispatch
//方式一:自己直接dispatch
this.$store.dispatch('personAbout/addPersonWang',person)
//方式二:借助mapActions读取
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'}),
  1. 开启命名空间后,组件中调用commit
//方式一:自己直接commit
this.$store.commit('personAbout/ADD_PERSON',person)
//方式二:借助mapMutations读取
...mapMutations('countAbout',{incrementOdd:'JIA',decrement:'JIAN'}),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值