目标:明确Vuex是什么,应用场景以及优势
Vuex 是一个 Vue 的 状态管理工具,状态就是数据。
大白话:Vuex 是一个插件,可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如:购物车数据 个人信息
某个状态 在 很多个组件 来使用 (个人信息)
多个组件 共同维护 一份数据 (购物车)
官方原文:
Vuex就像《近视眼镜》, 你自然会知道什么时候需要用它~
目标:基于脚手架创建项目,构建 vuex 多组件数据共享环境
效果是三个组件共享一份数据:
vue create vuex-demo
|-components
|--Son1.vue
|--Son2.vue
|-App.vue
App.vue
在入口组件中引入 Son1 和 Son2 这两个子组件
<template>
<div id="app">
<h1>根组件h1>
<input type="text">
<Son1>Son1>
<hr>
<Son2>Son2>
div>
template>
<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
export default {
name: 'app',
data: function () {
return {
}
},
components: {
Son1,
Son2
}
}
script>
<style>
#app {
width: 600px;
margin: 20px auto;
border: 3px solid #ccc;
border-radius: 3px;
padding: 10px;
}
style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
Son1.vue
<template>
<div class="box">
<h2>Son1 子组件h2>
从vuex中获取的值: <label>label>
<br>
<button>值 + 1button>
div>
template>
<script>
export default {
name: 'Son1Com'
}
script>
<style lang="css" scoped>
.box{
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
style>
Son2.vue
<template>
<div class="box">
<h2>Son2 子组件h2>
从vuex中获取的值:<label>label>
<br />
<button>值 - 1button>
div>
template>
<script>
export default {
name: 'Son2Com'
}
script>
<style lang="css" scoped>
.box {
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
style>
安装vuex与vue-router类似,vuex是一个独立存在的插件,如果脚手架初始化没有选 vuex,就需要额外安装。
yarn add vuex@3 或者 npm i vuex@3
store/index.js
专门存放 vuex 为了维护项目目录的整洁,在src目录下新建一个store目录其下放置一个index.js文件。 (和 router/index.js
类似)
store/index.js
// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)
// 创建仓库 store
const store = new Vuex.Store()
// 导出仓库
export default store
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
此刻起, 就成功创建了一个 空仓库!!
App.vue
created(){
console.log(this.$store)
}
明确如何给仓库 提供 数据,如何 使用 仓库的数据
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。
打开项目中的store.js文件,在state对象中可以添加我们要共享的数据。
// 创建仓库 store
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data,
// 区别:
// 1.data 是组件自己的数据,
// 2.state 中的数据整个vue项目的组件都能访问到
state: {
count: 101
}
})
问题: 如何在组件中获取count?
获取 store:
1.Vue模板中获取 this.$store
2.js文件中获取 import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx
组件中可以使用 $store 获取到vuex中的store对象实例,可通过state属性属性获取count, 如下
state的数据 - {{ $store.state.count }}
将state属性定义在计算属性中 https://vuex.vuejs.org/zh/guide/state.html
<h1>state的数据 - {{ count }}</h1>
// 把state中数据,定义在组件内的计算属性中
computed: {
count () {
return this.$store.state.count
}
}
//main.js
import store from "@/store"
console.log(store.state.count)
每次都像这样一个个的提供计算属性, 太麻烦了,我们有没有简单的语法帮我们获取state中的值呢?
mapState是辅助函数,帮助我们把store中的数据映射到 组件的计算属性中, 它属于一种方便的用法
用法 :
import { mapState } from 'vuex'
mapState(['count'])
上面代码的最终得到的是 类似于
count () {
return this.$store.state.count
}
computed: {
...mapState(['count'])
}
state的数据:{{ count }}
明确 vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据
Son1.vue
methods:{
handleAdd (n) {
// 错误代码(vue默认不会监测,监测需要成本)
this.$store.state.count++
// console.log(this.$store.state.count)
},
}
通过 strict: true
可以开启严格模式,开启严格模式后,直接修改state中的值会报错
const store = new Vuex.Store({
state: {
count: 0
},
// 定义mutations
mutations: {
}
})
mutations是一个对象,对象中存放修改state的方法
mutations: {
// 方法里参数 第一个参数是当前store的state属性
// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
addCount (state) {
state.count += 1
}
},
this.$store.commit('addCount')
1.在mutations中定义个点击按钮进行 +5 的方法
2.在mutations中定义个点击按钮进行 改变title 的方法
3.在组件中调用mutations修改state中的值
通过mutations修改state的步骤
1.定义 mutations 对象,对象中存放修改 state 的方法
2.组件中提交调用 mutations(通过$store.commit(‘mutations的方法名’))
掌握 mutations 传参语法
看下面这个案例,每次点击不同的按钮,加的值都不同,每次都要定义不同的mutations处理吗?
提交 mutation 是可以传递参数的 this.$store.commit('xxx', 参数)
mutations: {
...
addCount (state, count) {
state.count = count
}
},
handle ( ) {
this.$store.commit('addCount', 10)
}
小tips: 提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象
this.$store.commit('addCount', {
count: 10
})
实时输入,实时更新,巩固 mutations 传参语法
App.vue
export default {
methods: {
handleInput (e) {
// 1. 实时获取输入框的值
const num = +e.target.value
// 2. 提交mutation,调用mutation函数
this.$store.commit('changeCount', num)
}
}
}
store/index.js
mutations: {
changeCount (state, newCount) {
state.count = newCount
}
},
mapMutations和mapState很像,它把位于mutations中的方法提取了出来,我们可以将它导入
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['addCount'])
}
上面代码的含义是将mutations的方法导入了methods中,等价于
methods: {
// commit(方法名, 载荷参数)
addCount () {
this.$store.commit('addCount')
}
}
此时,就可以直接通过this.addCount调用了
但是请注意: Vuex中mutations中要求不能写异步代码,如果有异步的ajax请求,应该放置在actions中
state是存放数据的,mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化),
actions则负责进行异步操作
说明:mutations必须是同步的
需求: 一秒钟之后, 要给一个数 去修改state
对数据的改变还是要通过mutations,但是mutations对数据的修改是同步的,要异步修改数据可以通过actions,所以actions中只是做异步,对数据的修改还是通过调用mutations中的方法。
mutations: {
changeCount (state, newCount) {
state.count = newCount
}
}
actions: {
setAsyncCount (context, num) {
// 一秒后, 给一个数, 去修改 num
setTimeout(() => {
context.commit('changeCount', num)
}, 1000)
}
},
setAsyncCount () {
this.$store.dispatch('setAsyncCount', 666)
}
1.目标:掌握辅助函数 mapActions,映射方法
mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中
Son2.vue
import { mapActions } from 'vuex'
methods: {
...mapActions(['changeCountAction'])
}
//mapActions映射的代码 本质上是以下代码的写法
//methods: {
// changeCountAction (n) {
// this.$store.dispatch('changeCountAction', n)
// },
//}
直接通过 this.方法 就可以调用
除了state之外,有时我们还需要从state中筛选出符合条件的一些数据,这些数据是依赖state的,此时会用到getters
例如,state中定义了list,为1-10的数组,
state: {
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
组件中,需要显示所有大于5的数据,正常的方式,是需要list在组件中进行再一步的处理,但是getters可以帮助我们实现它
getters: {
// getters函数的第一个参数是 state
// 必须要有返回值
filterList: state => state.list.filter(item => item > 5)
}
{{ $store.getters.filterList }}
computed: {
...mapGetters(['filterList'])
}
{{ filterList }}