十次方项目前端,状态管理Vuex(九)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Eknaij/article/details/96480114

一、Vuex简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
快速理解:每个组件都有它自己数据属性,封装在data()中,每个组件之间data是完全隔离的,是私有的。如果我们需要各个组件都能访问到数据数据,或是需要各个组件之间能互相交换数据,这就需要一个单独存储的区域存放公共属性。这就是状态管理所要解决的问题。

二、快速入门

1.工程搭建

用cmd新建一个基于 webpack 模板的新项目

# 创建一个基于 webpack 模板的新项目
vue init webpack vuexdemo
# 安装依赖
cd vuexdemo
npm install
cnpm install --save vuex
#运行
npm run dev

2.读取状态值

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
实现步骤:
用CS打开vuexdemo
(1)在src下创建store,store下创建index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		count: 0
	}
})
export default store

(2)修改main.js,引入和装载store

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
	el: '#app',
	router,
	store,
	components: { App },
	template: '<App/>'
})

(3)修改components\HelloWorld.vue

<template>
	<div>
		{{$store.state.count}}
		<button @click="showCount">测试</button>
	</div>
	</template>
<script>
export default {
	methods:{
		showCount(){
			console.log(this.$store.state.count)
		}
	}
}
</script>

运行可以看到如下结果
在这里插入图片描述

3.改变状态值

你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
(1)修改store/index.js ,增加mutation定义

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})
export default store

(2)修改components\HelloWorld.vue ,调用mutation

<template>
	<div>
		{{$store.state.count}}
		<button @click="addCount">测试</button>
	</div>
</template>
<script>
export default {
	methods:{
		addCount(){
      this.$store.commit('increment')
			console.log(this.$store.state.count)
		}
	}
}
</script>

测试: 运行工程,点击测试按钮,我们会看到控制台和页面输出递增的数字
在这里插入图片描述
在这里插入图片描述

4.状态值共享测试

如果是另外一个页面,能否读取到刚才我在HelloWorld中操作的状态值呢?我们接下来就做一个测试
(1)在components下创建show.vue

<template>
    <div>
        show: {{$store.state.count}}
    </div>
</template>

(2)修改路由设置 router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Show from '@/components/Show'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/show',
      name: 'Show',
      component: Show
    }
  ]
})

测试: 在HelloWorld页面点击按钮使状态值增长,然后再进入show页面查看状态值

5. 提交载荷

所谓载荷(payload)就是 向 store.commit 传入额外的参数。
(1)修改store下的index.js

    ...
    mutations: {
        increment(state,x) {
            state.count += x
        }
    }
    ...

(2)修改HelloWorld.vue

......
addCount(){
	this.$store.commit('increment',10)
	console.log(this.$store.state.count)
}
......

6.Action

  • Action 类似于 mutation,不同在于:
  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
    我们现在使用 Action 来封装increment
    (1)修改store/index.js,添加一个actions
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    }

(2)修改HelloWorld.vue

<template>
    <div>
        show: {{$store.state.count}}
        <button @click="addCount">测试</button>
    </div>
</template>
<script>
export default {
    methods:{
        addCount(){
            this.$store.dispatch('increment')
            console.log(this.$store.state.count)
        }
    }
}
</script>

我们使用dispatch来调用action , Action也同样支持载荷

7.派生属性Getter

有时候我们需要从 store 中的 state 中派生出一些状态,例如我们在上例代码的基础上,我们增加一个叫 remark的属性,如果count属性值小于50则remark为加油,大于等于50小于100则remark为你真棒,大于100则remark的值为你是大神. 这时我们就需要用到getter为我们解决。
(1)修改store/index.js ,增加getters定义

    getters: {
        remark(state){
            if(state.count<50){
                return '加油'
            }else if( state.count<100){
                return '你真棒'
            }else{
                return '你是大神'
            }
        }
    }

Getter 接受 state 作为其第一个参数,也可以接受其他 getter 作为第二个参数
(2)修改HelloWorld.vue 显示派生属性的值

{{$store.getters.remark}}

在这里插入图片描述

三、模块化

1.Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割 .参见以下代码模型
在这里插入图片描述
我们现在就对工程按模块化进行改造
(1)修改store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


const moduleA ={
     state: {
        count: 0
    },
    mutations: {
        increment(state,x) {
            state.count += x
        }
    },
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    },
    getters: {
        remark(state){
            if(state.count<50){
                return '加油'
            }else if( state.count<100){
                return '你真棒'
            }else{
                return '你是大神'
            }
        }
    }
}
const store = new Vuex.Store({
    modules: {
        a:moduleA
    }
})
export default store   

(2)修改HelloWorld.vue和show.vue

{{$store.state.a.count}}

2.标准工程结构

如果所有的状态都写在一个js中,这个js必定会很臃肿,所以Vuex建议你按以下代码结构来构建工程
在这里插入图片描述
我们现在就按照上面的结构,重新整理以下我们的代码:
(1)store下创建modules文件夹,文件夹下创建a.js

export default {
     state: {
        count: 0
    },
    mutations: {
        increment(state,x) {
            state.count += x
        }
    },
    actions: {
        increment (context){
            context.commit('increment',10)
        }
    },
}
    
    

(2)store下创建getters.js

export default {
    remark: state => {
        if(state.a.count<50){
            return '加油'
        }else if( state.a.count<100){
            return '你真棒'
        }else{
            return '你是大神'
        }
    },
    count: state=> state.a.count
}
    

(3)修改store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import a from './modules/a'
import getters from './getters'
Vue.use(Vuex)

const store = new Vuex.Store({
    getters,
    modules: {
        a
    }
})
export default store   

(4)修改HelloWorld.vue

<template>
    <div>
        show: {{$store.getters.count}} {{$store.getters.remark}}
        <button @click="addCount">测试</button>
    </div>
</template>
<script>
export default {
    methods:{
        addCount(){
            this.$store.dispatch('increment')
            console.log(this.$store.getters.count)
        }
    }
}
</script>

猜你喜欢

转载自blog.csdn.net/Eknaij/article/details/96480114