0%

vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

笔记摘自:vuex最简单、最详细的入门文档

安装&使用

首先我们在 vue.js 2.0 开发环境中安装 vuex :

1
cnpm install vuex@3.0.0 --save

然后 , 在 main.js 中加入 :

1
2
3
4
5
6
7
import vuex from 'vuex'
Vue.use(vuex);
var store = new vuex.Store({//store对象
state:{
show:false
}
})

再然后 , 在实例化 Vue对象时加入 store 对象 :

1
2
3
4
5
6
7
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})

完成到这一步 , 在.vue文件中就可以通过 this.$store.state.show 来访问变量show。

单独文件

前面为了方便 , 我们把 store 对象写在了 main.js 里面 , 但实际上为了便于日后的维护 , 我们分开写更好 , 我们在 src 目录下 , 新建一个 store 文件夹 , 然后在里面新建一个 index.js :

1
2
3
4
5
6
7
8
9
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);

export default new vuex.Store({
state:{
show:false
}
})

那么相应的 , 在 main.js 里的代码应该改成 :

1
2
3
4
5
6
7
8
9
10
//vuex
import store from './store'

new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})

要是变量很大怎么办呢,放在index.js中会显得很臃肿,我们可以使用vuex的modules

modules

组件多了之后 , 状态也多了 , 这么多状态都堆在 store 文件夹下的 index.js 不好维护怎么办 ?我们可以使用 vuex 的 modules , 把 store 文件夹下的 index.js 改成 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);

import localData from './localData.js';//引入某个store对象

export default new vuex.Store({
//使用module来分类管理数据,state可要可不要
//this.$store.state.变量名
state:{
show:false
},
modules: {
//本地离线数据(数据量过大,单独放在一个js文件中,作为module引入)
//this.$store.state.module名.变量名
localData: localData
}
})

这里我们引用了一个 localData.js :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default {
state: {
account: [{
name: 'admin',
pwd: '123456',
icon: '../../../images/markdown_img/2020/20210502162645.jpg'
}, {
name: 'pete',
pwd: '123456',
icon: '../../../images/markdown_img/2020/20210502162745.jpg'
}]
}
}

//使用时,通过 this.$store.state.localData.account 访问此处的变量account
若图片不能正常显示,请在浏览器中打开

欢迎关注我的其它发布渠道