第 5 章:vuex

1. 理解 vuex

vuex 是什么:

  1. 概念:专门在 Vue 中实现集中式状态(数据)管理的一个 Vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
  2. Github 地址: https://github.com/vuejs/vuex

什么时候使用 Vuex

  1. 多个组件依赖于同一状态(数据)
  2. 来自不同组件的行为需要变更同一状态(数据)
  3. 多个组件需要共享数据时
  • 工作原理图:
    在这里插入图片描述

2. vuex 的 API

2.1 state

  1. vuex 管理的状态对象
  2. 它应该是唯一的
  3. 示例代码:
const state = {xxx: initValue
}

2.2 actions

  1. 值为一个对象,包含多个响应用户动作的回调函数
  2. 通过 commit( )来触发 mutation 中函数的调用, 间接更新 state

如何触发 actions 中的回调?

  • 在组件中使用: $store.dispatch('对应的 action 回调名')触发
  • 可以包含异步代码(定时器, ajax 等等)

示例代码:

const actions = {zzz ({commit, state}, data1) {commit('yyy', {data1})}
}

2.3 mutations

  1. 值是一个对象,包含多个直接更新 state 的方法
  2. 谁能调用 mutations 中的方法?如何调用?
    在 action 中使用:commit('对应的 mutations 方法名')触发
  3. mutations 中方法的特点:不能写异步代码、只能单纯的操作 state
  4. 示例代码:
const mutations = {yyy (state, {data1} {// 更新state的某个属性}
}

2.4 getters

  1. 值为一个对象,包含多个用于返回数据的函数
  2. 如何使用:$store.getters.xxx
  3. 示例代码:
const getters = {mmm (state) {return state.msg + '!'}
}

2.5 modules

  1. 包含多个 module
  2. 一个 module 是一个 store 的配置对象
  3. 与一个组件(包含有共享数据)对应

3. 搭建 vuex 环境

  1. 创建文件:src/store/index.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions对象——响应组件中用户的动作
const actions = {}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}//创建并暴露store
export default new Vuex.Store({actions,mutations,state
})
  1. main.js中创建vm时传入store配置项
......
//引入store
import store from './store'
......//创建vm
new Vue({el:'#app',render: h => h(App),store
})

4. vuex 基本使用

  1. 初始化数据、配置actions、配置mutations,操作文件store.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引用Vuex
Vue.use(Vuex)const actions = {//响应组件中加的动作jia(context,value){// console.log('actions中的jia被调用了',miniStore,value)context.commit('JIA',value)},
}const mutations = {//执行加JIA(state,value){// console.log('mutations中的JIA被调用了',state,value)state.sum += value}
}//初始化数据
const state = {sum:0
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,
})
  1. 组件中读取vuex中的数据:$store.state.sum
  2. 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)
  • 备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

5. getters 的使用

  • 概念:当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工。
  • store.js中追加getters配置:
......const getters = {bigSum(state){return state.sum * 10}
}//创建并暴露store
export default new Vuex.Store({......getters
})
  • 组件中读取数据:$store.getters.bigSum

6. 四个 map 方法的使用

6.1 mapState方法

  • 用于帮助我们映射state中的数据为计算属性
computed: {//借助mapState生成计算属性:sum、school、subject(对象写法)...mapState({sum:'sum',school:'school',subject:'subject'}),//借助mapState生成计算属性:sum、school、subject(数组写法)...mapState(['sum','school','subject']),
},

6.2 mapGetters方法

  • 用于帮助我们映射getters中的数据为计算属性
computed: {//借助mapGetters生成计算属性:bigSum(对象写法)...mapGetters({bigSum:'bigSum'}),//借助mapGetters生成计算属性:bigSum(数组写法)...mapGetters(['bigSum'])
},

6.3 mapActions方法

  • 用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数
methods:{//靠mapActions生成:incrementOdd、incrementWait(对象形式)...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})//靠mapActions生成:incrementOdd、incrementWait(数组形式)...mapActions(['jiaOdd','jiaWait'])
}

6.4 mapMutations方法

  • 用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数
methods:{//靠mapActions生成:increment、decrement(对象形式)...mapMutations({increment:'JIA',decrement:'JIAN'}),//靠mapMutations生成:JIA、JIAN(对象形式)...mapMutations(['JIA','JIAN']),
}

6.5 备注

mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

7. 模块化+命名空间

  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}
})
  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',{increment:'JIA',decrement:'JIAN'}),

8. 求和案例

在这里插入图片描述

8.1 求和案例_纯 vue 版

8.1.1 App.vue
<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},}
</script>
8.1.2 Count.vue
<template><div><h1>当前求和为:{{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, //用户选择的数字sum:0 //当前的和}},methods: {increment(){this.sum += this.n},decrement(){this.sum -= this.n},incrementOdd(){if(this.sum % 2){this.sum += this.n}},incrementWait(){setTimeout(()=>{this.sum += this.n},500)},},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.1.3 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),beforeCreate() {Vue.prototype.$bus = this}
})

8.2 求和案例_vuex 版

8.2.1 App.vue
<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},mounted() {// console.log('App',this)},}
</script>
8.2.2 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('JIA',this.n)},decrement(){this.$store.commit('JIAN',this.n)},incrementOdd(){this.$store.dispatch('jiaOdd',this.n)},incrementWait(){this.$store.dispatch('jiaWait',this.n)},},mounted() {console.log('Count',this)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.2.3 index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}
}
//准备mutations——用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value}
}
//准备state——用于存储数据
const state = {sum:0 //当前的和
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,
})
8.2.4 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

8.3 求和案例_getters

8.3.1 App.uve
<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},mounted() {// console.log('App',this)},}
</script>
8.3.2 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('JIA',this.n)},decrement(){this.$store.commit('JIAN',this.n)},incrementOdd(){this.$store.dispatch('jiaOdd',this.n)},incrementWait(){this.$store.dispatch('jiaWait',this.n)},},mounted() {console.log('Count',this.$store)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.3.3 index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}
}
//准备mutations——用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value}
}
//准备state——用于存储数据
const state = {sum:0 //当前的和
}
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state){return state.sum*10}
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
})
8.3.4 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

8.4 求和案例_mapState 与 mapGetters

8.4.1 App.uve
<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},mounted() {// console.log('App',this)},}
</script>
8.4.2 Count.vue
<template><div><h1>当前求和为:{{sum}}</h1><h3>当前求和放大10倍为:{{bigSum}}</h3><h3>我在{{school}},学习{{subject}}</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, //用户选择的数字}},computed:{//靠程序员自己亲自去写计算属性/* sum(){return this.$store.state.sum},school(){return this.$store.state.school},subject(){return this.$store.state.subject}, *///借助mapState生成计算属性,从state中读取数据。(对象写法)// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(['sum','school','subject']),/* ******************************************************************** *//* bigSum(){return this.$store.getters.bigSum}, *///借助mapGetters生成计算属性,从getters中读取数据。(对象写法)// ...mapGetters({bigSum:'bigSum'})//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(['bigSum'])},methods: {increment(){this.$store.commit('JIA',this.n)},decrement(){this.$store.commit('JIAN',this.n)},incrementOdd(){this.$store.dispatch('jiaOdd',this.n)},incrementWait(){this.$store.dispatch('jiaWait',this.n)},},mounted() {const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})console.log(x)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.4.3 index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}
}
//准备mutations——用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value}
}
//准备state——用于存储数据
const state = {sum:0, //当前的和school:'尚硅谷',subject:'前端'
}
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state){return state.sum*10}
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
})
8.4.4 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

8.5 求和案例_mapMuatations 与 mapActions

8.5.1 App.uve
<template><div><Count/></div>
</template><script>import Count from './components/Count'export default {name:'App',components:{Count},mounted() {// console.log('App',this)},}
</script>
8.5.2 Count.vue
<template><div><h1>当前求和为:{{sum}}</h1><h3>当前求和放大10倍为:{{bigSum}}</h3><h3>我在{{school}},学习{{subject}}</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, //用户选择的数字}},computed:{//借助mapState生成计算属性,从state中读取数据。(对象写法)// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(['sum','school','subject']),/* ******************************************************************** *///借助mapGetters生成计算属性,从getters中读取数据。(对象写法)// ...mapGetters({bigSum:'bigSum'})//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(['bigSum'])},methods: {//程序员亲自写方法/* increment(){this.$store.commit('JIA',this.n)},decrement(){this.$store.commit('JIAN',this.n)}, *///借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations({increment:'JIA',decrement:'JIAN'}),//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)// ...mapMutations(['JIA','JIAN']),/* ************************************************* *///程序员亲自写方法/* incrementOdd(){this.$store.dispatch('jiaOdd',this.n)},incrementWait(){this.$store.dispatch('jiaWait',this.n)}, *///借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)// ...mapActions(['jiaOdd','jiaWait'])},mounted() {const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})console.log(x)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.5.3 index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}
}
//准备mutations——用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value}
}
//准备state——用于存储数据
const state = {sum:0, //当前的和school:'尚硅谷',subject:'前端'
}
//准备getters——用于将state中的数据进行加工
const getters = {bigSum(state){return state.sum*10}
}//创建并暴露store
export default new Vuex.Store({actions,mutations,state,getters
})
8.5.4 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

8.6 求和案例_多组件共享数据

8.6.1 App.uve
<template><div><Count/><hr><Person/></div>
</template><script>import Count from './components/Count'import Person from './components/Person'export default {name:'App',components:{Count,Person},mounted() {// console.log('App',this)},}
</script>
8.6.2 Count.vue
<template><div><h1>当前求和为:{{sum}}</h1><h3>当前求和放大10倍为:{{bigSum}}</h3><h3>我在{{school}},学习{{subject}}</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, //用户选择的数字}},computed:{//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(['sum','school','subject','personList']),//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(['bigSum'])},methods: {//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations({increment:'JIA',decrement:'JIAN'}),//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})},mounted() {// const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})// console.log(x)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.6.3 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>
8.6.4 index.js
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)//准备actions——用于响应组件中的动作
const actions = {/* jia(context,value){console.log('actions中的jia被调用了')context.commit('JIA',value)},jian(context,value){console.log('actions中的jian被调用了')context.commit('JIAN',value)}, */jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}
}
//准备mutations——用于操作数据(state)
const mutations = {JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value},ADD_PERSON(state,value){console.log('mutations中的ADD_PERSON被调用了')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
})
8.6.5 main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

8.7 vuex 模块化编码

8.7.1 App.vue

path:root

<template><div><Count/><hr><Person/></div>
</template><script>import Count from './components/Count'import Person from './components/Person'export default {name:'App',components:{Count,Person},mounted() {// console.log('App',this)},}
</script>
8.7.2 Count.vue

path:root/components

<template><div><h1>当前求和为:{{sum}}</h1><h3>当前求和放大10倍为:{{bigSum}}</h3><h3>我在{{school}},学习{{subject}}</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, //用户选择的数字}},computed:{//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState('countAbout',['sum','school','subject']),...mapState('personAbout',['personList']),//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters('countAbout',['bigSum'])},methods: {//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})},mounted() {console.log(this.$store)},}
</script><style lang="css">button{margin-left: 5px;}
</style>
8.7.3 Person.vue

path:root/components

<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="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:'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 = ''},addPersonServer(){this.$store.dispatch('personAbout/addPersonServer')}},}
</script>
8.7.4 Count.js

path:root/store

//求和相关的配置
export default {namespaced:true,actions:{jiaOdd(context,value){console.log('actions中的jiaOdd被调用了')if(context.state.sum % 2){context.commit('JIA',value)}},jiaWait(context,value){console.log('actions中的jiaWait被调用了')setTimeout(()=>{context.commit('JIA',value)},500)}},mutations:{JIA(state,value){console.log('mutations中的JIA被调用了')state.sum += value},JIAN(state,value){console.log('mutations中的JIAN被调用了')state.sum -= value},},state:{sum:0, //当前的和school:'尚硅谷',subject:'前端',},getters:{bigSum(state){return state.sum*10}},
}
8.7.5 index.js

path:root/store

//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//应用Vuex插件
Vue.use(Vuex)//创建并暴露store
export default new Vuex.Store({modules:{countAbout:countOptions,personAbout:personOptions}
})
8.7.6 person.js

path:root/store

//人员管理相关的配置
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('https://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:'张三'}]},getters:{firstPersonName(state){return state.personList[0].name}},
}
8.7.7 main.js

path:root

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//引入store
import store from './store'//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)//创建vm
new Vue({el:'#app',render: h => h(App),store,beforeCreate() {Vue.prototype.$bus = this}
})

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/56807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ant design vue TimePicker时间选择器不点击确认也可以设置值

文章目录 前言一、背景二、操作步骤1.复现前的准备工作&#xff08;1&#xff09;vue版本和ant design vue 版本&#xff08;2&#xff09;任意ant design vue TimePicker的demo 2.解决问题&#xff08;1&#xff09;使用change时间&#xff08;无效&#xff09;&#xff08;2&…

DEV C++自动补全文件头的设置操作

第一步&#xff1a;打开DEV C 第二步&#xff1a;打开“工具” 第三步&#xff1a;点击“编辑器属性” 第四步&#xff1a;点击“代码” 第五步&#xff1a;点击“缺省源” 第六步&#xff1a;输入常用的文件头代码&#xff1a; 例如&#xff1a; #include<bits/stdc.h&g…

数据结构(JAVA)包装类泛型

文章目录 包装类基本数据类型和对应的包装类装箱和拆箱面试题 泛型什么是泛型泛型的语法泛型类的使用泛型的使用裸类型(Raw Type) &#xff08;仅需了解&#xff09;擦除机制泛型的上界泛型方法 包装类 基本数据类型和对应的包装类 注意&#xff0c;除了int基本数据类型的包装…

OracleT5-2 Solaris11安装

1、Solaris11安装 在光驱中插入Solaris11的光盘后,在ok提示中boot cdrom {0} ok boot cdrom NOTICE: Entering OpenBoot. NOTICE: Fetching Guest MD from HV. NOTICE: Starting additional cpus. NOTICE: Initializing LDC services. NOTICE: Probing PCI devices. N…

玄机平台-应急响应-webshell查杀

首先xshell连接 然后进入/var/www/html目录中&#xff0c;将文件变成压缩包 cd /var/www/html tar -czvf web.tar.gz ./* 开启一个http.server服务&#xff0c;将文件下载到本地 python3 -m http.server 放在D盾中检测 基本可以确认木马文件就是这四个 /var/www/html/shell.p…

初识MySQL · 数据库

目录 前言&#xff1a; 数据库 简单使用 存储引擎 前言&#xff1a; 本文也是MySQL的第一篇文章了&#xff0c;新的知识点已经出现&#xff0c;怎么能够停止不前&#xff0c;穿越时空……(迪迦奥特曼乱入哈哈哈)。 言归正传&#xff0c;我们在本文的目标有&#xff1a; …

Flink CDC同步mysql数据到doris

前置参考 flink快速安装&#xff1a;Flink入门-CSDN博客 doris快速安装&#xff1a;Apache Doris快速安装-CSDN博客 Flink CDC简介 Flink CDC 是一个基于流的数据集成工具&#xff0c;旨在为用户提供一套功能更加全面的编程接口&#xff08;API&#xff09;。 该工具使得用户能…

洞察云上风险,主机安全尽在掌握

在实战攻防演练中&#xff0c;主机一直是攻击方的最终目标。作为网络架构中的重要组成部分&#xff0c;主机包含了大量的敏感数据、关键服务和系统资源。同时主机拥有网络资源的访问权限&#xff0c;攻击者通过入侵主机获得权限&#xff0c;进而控制整个网络或系统。因此做好主…

vue2 Canvas 多边形区域绘制组件封装

效果预览&#xff1a; CanvasBox组件 <!-- 区域设置canvas --> <template><div class"all" ref"divideBox"><!-- <div><button click"test">清空</button></div> --><img id"img"…

Ubuntu中MySQL远程登录设置

mysql单独放在一台Ubuntu服务器上&#xff0c;我远程连接不上。可能是安装的时候忘记设置远程登录了。事后补救措施如下&#xff1a; MySQL 绑定地址配置问题 MySQL 可能只绑定了 localhost&#xff0c;无法接受来自外部主机的连接。你需要检查 MySQL 的配置文件 /etc/mysql/…

使用Vscode配置ftp连接远程服务器(上传本地文件)

1.安装插件 扩展商店搜sftp,点击进行安装。 2.配置json文件 crtl+shift+p 输入ftp配置命令 sftp:config {"name": "My Server", //设置名字"host": "localhost"</

腐蚀膨胀预处理

腐蚀&#xff1a;通过减少前景对象&#xff08;例如白色字符&#xff09;的边缘&#xff0c;腐蚀可以用来减小或消除细小的干扰线。如果干扰线较细&#xff0c;腐蚀可以有效地“消除”这些线条&#xff0c;同时保留较粗的字符。 膨胀&#xff1a;在腐蚀之后&#xff0c;膨胀可…

TCP——Socket

应用进程只借助Socket API发和收但是不关心他是怎么进行传和收的 数据结构 图示Socket连接 捆绑属于隐式捆绑

数据驱动时代:五款免费报表工具深度解析

在当今数据驱动的时代&#xff0c;报表工具已经成为各类企业进行决策和管理的重要工具。无论是大中型企业还是小微企业&#xff0c;能够快速、高效地生成可视化报表&#xff0c;洞察业务运营情况&#xff0c;已经成为提升竞争力的关键。今天为大家挑选了5款非常优秀的报表软件&…

Autosar软件组件概述

AUTOSAR中的应用软件设计为独立的软件单元&#xff0c;即软件组件类型&#xff08;SwComponentTypes&#xff09;&#xff0c;封装了相关功能和行为的实现&#xff0c;并通过端口原型&#xff08;PortPrototypes&#xff09;&#xff0c;向外部暴露自己。 AUTOSAR 标准应用了设…

std::setw中文不能对齐的问题

从别的博主那 copy过来 记录下 #include <codecvt> #include <locale>class chs_codecvt : public std::codecvt_byname<wchar_t, char, std::mbstate_t> {public:chs_codecvt() : codecvt_byname("zh_CN.GBK") {} };int encoding_diff(string …

xtu oj 原根

文章目录 回顾杂思路c 语言代码 回顾 AB III问题 H: 三角数问题 G: 3个数等式 数组下标查询&#xff0c;降低时间复杂度1405 问题 E: 世界杯xtu 数码串xtu oj 神经网络xtu oj 1167 逆序数&#xff08;大数据&#xff09; 杂 有一些题可能是往年的程设的题&#xff0c;现在搬到…

Higress 重磅更新:AI 能力全面开源,云原生能力再升级

作者&#xff1a;澄潭、钰诚 新版本简介 Higress 最新的 1.4 版本基于为通义千问&#xff0c;以及多家云上 AGI 厂商客户提供 AI 网关的积累沉淀&#xff0c;开源了大量 AI 原生的网关能力。同时也在 Ingress、可观测、流控等云原生能力上做了全方位升级&#xff1a; AI 能力…

VS code部署Vue项目Demo

在之前已经在IDEA中部署过vue项目demo。本次在上次基础上进行。 IDEA中Vue的安装和使用【window10】_idea安装vue-CSDN博客 步骤一、安装VSCode 双击安装即可 步骤二&#xff1a;检查npm是否安装 步骤三&#xff1a;检查vue是否安装 &#xff08;vue create 项目名 只要在v…

Leetcode 单词规律

即判断给定的模式字符串&#xff08;pattern&#xff09;和单词字符串&#xff08;s&#xff09;是否遵循相同的对应规则。具体来说&#xff0c;就是要判断 pattern 中的字符与 s 中的单词是否存在一一对应的关系&#xff0c;即双射&#xff08;bijection&#xff09;。 算法思…