什么是vuex?
1 state : 统一的定义公共数据
2 mutations : 使用它来修改数据(类似于methods)
3 getters : 类似于computed(计算属性 , 对现有的数据进行计算得到新的数据----派生)
4 actions : 发起异步请求(axios)
5 modules : 拆分模块
1 安装 它是一个独立的包 , 需要先安装
2 配置
a. 创建Vuex.store实例
b. 向Vue实例注入store
3 使用 在组件中使用store
实例化store
在store/index.js中放置的代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state(){
return {
// 就是公共的数据,所有的组件都可以直接使用
count: 100
}
},
mutations: {
},
getters: {
},
actions: {
},
modules: {
}
})
export default store
向Vue实例注入store
//其他省略
// 1. 导入store
import store from './store/index.js'
new Vue({
store,//2. 注入Vue实例
//其他省略
render: h => h(App),
}).$mount('#app')
在组件中使用store
在任意组件中,通过 this.$store.state 来获取公共数据。
Vuex-state
new Vuex.store({
state() {
return {
属性名: 属性值
}
}
})
new Vuex.store({
state(){
return {
userInfo: {
name: '胡歌之江西分歌',
skills: ['抖音', 'B站', '美团'],
address: '江西高安',
logo: 'https://vuejs.org/images/logo.svg'
// https://www.runoob.com/wp-content/uploads/2016/02/react.png
}
}
}
})
在组件中,通过this.$store.state.属性名
来访问。
正在上传…重新上传取消正在上传…重新上传取消正在上传…重新上传取消编辑vue-devtool调试工具
Vuex-mutations
new Vue.store({
// 省略其他...
mutations:{
// 每一项都是一个函数,可以声明两个形参
mutation名1:function(state,形参) {
},
mutation名2:function(state,形参) {
}
}
})
每一项都是一个函数,可以声明两个形参:
- 第一个参数是必须的,表示当前的state。在使用时不需要传入
- 第二个参数是可选的,表示载荷,是可选的。在使用时要传入的数据
格式 :
this.$store.commit('mutation名', 实参)
在store/index.js
中,补充:
- 数据项
- 更新数据项url的mutations
export default new Vuex.Store({
// state: 用来保存所有的公共数据
state: {
userInfo: {
name: '胡歌',
skills: ['抖音', 'B站', '美团'],
address: '江西高安',
logo: 'https://vuejs.org/images/logo.svg'
// https://www.runoob.com/wp-content/uploads/2016/02/react.png
}
},
// mutations: 用它提供修改数据的方法
// 中文是:变化,异动。
// 数据不应该在组件内部直接修改,必须在组件内调用mutations来修改
mutations: {
setLogo(state, newUrl) {
state.userInfo.logo = newUrl
}
}
}
在组件中,调用
const url = 'http://s02.mifile.cn/assets/static/image/logo-mi2.png'
this.$store.commit('changeUrl', url)
图例
总结 :
mutations的中文含义是:变异。 它是Vuex中用来修改公共数据的唯一入口。
在定义时:它的第一个参数是state,第二个参数是超参数
在调用时:用 this.$store.commit('mutation名', 参数) 来调用
Vuex-mutaions拓展理解
问:为啥是$store.commit('mutations的名字')而不是$store.mutations的名字()?
答:Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
问:数据不可以该在组件内部直接修改吗?
答:不能。虽然语法上不报错,也有响应式的特点。但是不推荐。特别是在严格模式下会报错。若将vue创建 store 的时候传入 strict: true, 开启严格模式,那么任何修改state的操作,只要不经过 mutation的函数,vue就会报错
问:可以传递多个数据吗?
答:参数只能有一个:下面的写法是不对的:
this.$store.commit('setUrl', url, host) // host这个参数将无法被接收到
如果希望传递复杂的数据,第二个参数可以是对象,例如下面的写法
this.$store.commit('setUrl', { url, host} )
发请求取数据做保存
思路
组件created钩子函数中:
- 发ajax请求(用axios库),获取数据
- 调用mutations保存数据到vuex
- 在组件中使用数据
在app.vue(或者其他的组件)中,created钩子函数中的代码如下:
created(){
// console.log(this.$store.state.count)
this.loadData()
},
methods: {
async loadData(){
// 1. 发请求拿数据
const res = await axios.get('http://www.xxxxxxxxx:3009/api/getbooks')
console.log(res.data.data)
// 2. 把数据保存到vuex(state)
this.$store.commit('initBooks', res.data.data)
}
},
在src/store/index.js
中,补充对应的数据项 books和操作的方法。
state: {
// 省略其他...
books: [] // 用来保存书
},
mutations: {
// 省略其他...
// 用来设置数据
initBooks(state, books) {
state.books = books
}
}
app.vue
模板中 渲染数据
<div style="flex: 1 1 auto; border:1px solid #ccc;">
书目
<p v-for="(book, idx) in $store.state.books" :key="idx">
{{book.name}}, {{book.price}}
</p>
总价为:XX元
</div>
实例图如下 :
Vuex-用getters的派生状态
作用 : 在state中的数据的基础上,进一步对数据进行加工得到新数据。(与组件中computed一样)
图例如下 :
例如 : 计算总价
new Vuex.store({
state: {
books: [
{
"name": "javasript技术内幕",
"price": 100,
"img": "https://img3m7.ddimg.cn/64/26/29120617-1_u_8.jpg"
},
{
"name": "数学之美",
"price": 44,
"img": "https://img3m2.ddimg.cn/18/30/28538352-1_b_5.jpg"
},
{
"name": "认知天性",
"price": 40,
"img": "https://img3m3.ddimg.cn/74/33/1732997153-3_u_3.jpg"
}
]
}
})
格式 :
new Vuex.store({
// 省略其他...
getters: {
// state 就是上边定义的公共数据state
getter的名字1: function(state) {
return 要返回的值
}
}
})
使用 : 在组件中通过:$store.getters.getter的名字
来访问
Vuex-actions-发异步请求
actions介绍
- actions是vuex的一个配置项
- 作用:发异步请求获取数据,调用mutations来保存数据,将整个ajax操作封装到Vuex的内部
- 要点:
actions内部可以发异步请求操作
actions是间接修改state的:是通过调用 mutation来修改state
格式 :
new Vuex.store({
// 省略其他...
actions: {
// context对象会自动传入,它与store实例具有相同的方法和属性
action的名字: function(context, 参数) {
// 1. 发异步请求, 请求数据
// 2. commit调用mutation来修改数据
// context.commit('mutation名', 参数)
}
}
})
使用 : 在组件中通过this.$store.dispatch('actions的名字', 参数)
来调用action
修改上面例子中的发请求图书的代码,将axios的部分写到action中
// 发ajax请求,从后端获取数据,再来去修改state中的数据
actions: {
getBooks (context) {
// 1. 发异步请求
axios({
url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books',
method: 'GET'
}).then(res => {
console.log(res)
// 2. 调用mutation
context.commit('setBooks', res.data.data)
})
}
},
图示如下 :
将ajax请求放在actions中有两个好处:
- 代码得到了进一步封装。将发ajax和保存数据到vuex绑定在一起。
- 逻辑更通顺。如果数据需要保存在Vuex的state中,那从接口处获取数据的操作就定义在Vuex的actions中。
图例如下 :
Vuex-用modules来拆分复杂业务
modules的作用 : 拆分模块,把复杂的场景按模块来拆开
格式 :
export default new Vuex.Store({
// state: 用来保存所有的公共数据
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
模块名1: {
// namespaced为true,则在使用mutations时,就必须要加上模块名
namespaced: true,
state: {},
getters: {},
mutations: {},
actions: {},
modules: {}
},
模块名2: {
// namespaced不写,默认为false,则在使用mutations时,不需要加模块名
state: {},
getters: {},
mutations: {},
actions: {},
modules: {}
}
}
})
目录 :
|--store /
|------- index.js # 引入模块
|------- modules
|-------------- / mod1.js # 模块1
|-------------- / mod2.js # 模块2
访问数据和修改数据的调整
访问模块中的数据,要加上模块名
获取数据项: {{$store.state.模块名.数据项名}}
获取getters: {{$store.getters['模块名/getters名']}}
访问模块中的mutations/actions:
1.如果namespaced为true,则需要额外去补充模块名
2.如果namespaced为false,则不需要额外补充模块名
$store.commit('mutations名') // namespaced为false
$store.commit('模块名/mutations名') // namespaced为true$store.dispatch('actions名') // namespaced为false
$store.dispatch('模块名/actions名') // namespaced为true
vuex-用modules之后代码结构优化
图例如下 :
示例图如下 :
Vuex-辅助函数mapState来使用公共数据
目的 : 将state中的变量映射到当前的组件中使用;
当访问某个数据项嵌套太深了,能不能优化一下访问的方式?
答:用mapState把公共数据(vuex.store) 映射 到本组件内部的计算属性中
mapState的使用步骤
映射
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
// es6 按需导入 import { mapState } from 'vuex'
import { mapState } from 'vuex'
computed: {
// 说明1: ...对象 是把对象展开,合并到computed
// 说明2: mapState是一个函数
// ['数据项1', '数据项2']
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
使用 :
this.xxx
{{xxx}}
实例 :
// 步骤
// 1. 导入辅助函数mapState,它是在vuex中定义的一个工具函数。
// es6 按需导入 import { mapState } from 'vuex'
import { mapState } from 'vuex'
// 2. 在computed中使用 ...mapState(['books'])
// const res = mapState(['books'])
// res的结果是一个对象: { books: function() {}}
// console.log('mapState', res)
export default {
computed: {
c1 () {
return 'c1'
},
// books: function() {}
// ..res: 把res这个对象合并到computed对象中
// ...res
...mapState(['books'])
}
}
</script>
总结 :
- mapState是辅助函数,将vuex中的数据投射到组件内部;
- computed:{ ...mapState() } 这里的...是对象的展开运算符,整体来看是对象的合并。
Vuex-辅助函数mapState对数据重命名
场景 : vuex中的数据与本组件内的数据名相同
格式 :
...mapState({'新名字': 'xxx'})
Vuex-map函数用法汇总
如何使用全局state
- 直接使用: this.$store.state.xxx;
- map辅助函数:
-
computed: { // 省略其他计算属性 ...mapState(['xxx']), ...mapState({'新名字': 'xxx'}) }
如何使用modules中的state
- 直接使用: this.$store.state.模块名.xxx;
- map辅助函数:
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
如何使用全局getters
- 直接使用:
this.$store.getters.xxx
- map辅助函数:
computed: {
...mapGetters(['xxx']),
...mapGetters({'新名字': 'xxx'})
}
如何使用modules中的getters
- 直接使用:
this.$store.getters.模块名.xxx
- map辅助函数:
computed: {
...mapGetters('模块名', ['xxx']),
...mapGetters('模块名',{'新名字': 'xxx'})
}
如何使用全局mutations
- 直接使用:
this.$store.commit('mutation名', 参数)
- map辅助函数:
methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
如何使用modules中的mutations(namespaced:true)
- 直接使用:
this.$store.commit('模块名/mutation名', 参数)
- map辅助函数:
methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
如何使用全局actions
- 直接使用:
this.$store.dispatch('action名', 参数)
- map辅助函数:
methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
如何使用modules中的actions(namespaced:true)
- 直接使用:
this.$store.dispatch('模块名/action名', 参数)
- map辅助函数:
methods: {
...mapActions('模块名', ['xxx']),
...mapActions('模块名',{'新名字': 'xxx'})
}
actions和mutations和state的关系图如下 :
核心API小结关系图如下 :