vuex中的state
本文讲解vuex中的state使用方法。
入门讲解
首先第一步肯定是创建vue项目,具体操作看这篇文章:用命令窗口的方式创建Vue项目
首先在store文件夹下面,创建一个state.js文件,存放公共的数据
在store文件夹下面的index.js文件中进行如下配置。
然后前端可以采取这两种写法,就可以访问到存储的数据了。
所以我们可以知道的是这个state.js就是用来存放数据的。
mapState辅助函数
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <div class = "about" > <h1>This is an about page</h1> {{ $store.state.str }} <hr> {{ str }} <hr> {{ a }} <hr> {{ b }} </div> import { mapState } from 'vuex' export default { computed: { ...mapState([ 'str' , 'a' , 'b' ]) } } |
运行结果:
案例
好的,在不增加难度的情况下,我来给您修改一下之前的案例。
案例 1:在线状态
- 思路
1 2 3 4 5 | const store = new Vuex.Store({ state: { onlineStatus: false } }) |
这里我们定义了一个名为 onlineStatus
的属性,并初始化为 false
。
当用户上线时,可以更新 onlineStatus
属性:
1 | store.state.onlineStatus = true |
这将直接更改 onlineStatus
属性中的值。
然后,你可以通过其他组件调用此值:
1 2 3 4 5 | computed: { onlineStatus() { return this .$store.state.onlineStatus } } |
完整代码
- 项目结构
- state.js
1 2 3 | export default { onlineStatus: false } |
- index.js
1 2 3 4 5 6 7 8 9 10 11 | import { createStore } from 'vuex' import state from './state' export default createStore({ state, mutations: { SET_ONLINE_STATUS (state, status) { state.onlineStatus = status } } }) |
- TestView.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div> <p>Your online status is {{ onlineStatusText }}</p> </div> export default { computed: { onlineStatusText () { return this .$store.state.onlineStatus ? 'Online' : 'Offline' } } } /* 样式可以选择添加 */ |
案例 2:主题样式
- 思路
1 2 3 4 5 | const store = new Vuex.Store({ state: { themeColor: 'blue' } }) |
我们定义了一个名为 themeColor
的属性,并用 "blue"
初始化它。
为了更改主题颜色,可以直接设置 themeColor
的值:
1 | store.state.themeColor = 'red' |
这将直接更改我们的主题颜色值。
然后,你可以通过其他组件调用此值:
1 2 3 4 5 | computed: { themeColor() { return this .$store.state.themeColor } } |
完整代码
- state.js
1 2 3 4 | export default { onlineStatus: false , themeColor: 'blue' } |
- index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import { createStore } from 'vuex' import state from './state' export default createStore({ state, mutations: { SET_ONLINE_STATUS (state, status) { state.onlineStatus = status }, SET_THEME_COLOR (state, color) { state.themeColor = color } } }) |
- TestView.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <div> <p>Your theme color is {{ themeColor }}</p> <button>Change Theme Color</button> </div> export default { computed: { themeColor () { return this .$store.state.themeColor } }, methods: { changeThemeColor () { this .$store.state.themeColor = 'red' } } } /* 样式可以自定义 */ |
运行结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。