vue项目中使用vuex存储变量
前记
因为项目前端需要访问后端的api, 在写axios的时候发现有写了几个地方都是同一个api连接, 于是就想写入”配置文件”中以便直接读取和解耦. 在vue的官方文档中驰骋了一会, 发现因为版本不一样, 不知道怎么引入项目, 当场裂开. 好在后来还是找到了.
(主要怕自己下次忘了所以记一下)
环境
vue3
@vue/cli 4.5.12
简单使用
- 创建store文件夹位于
project/src/
, 文件夹内有一个index.js文件 - 在state中写入要存储的变量
1 | store/index.js |
- 在main.js中使用store
因为版本的差异 , 我项目中使用的是createApp.use(store)
1 | // main.js |
而网上有一些版本则是new Vue()
1 | // 其他版本 |
- 在component中使用$store.state.var获取变量
1 | <template> |
在console.log(this.$store.state.food)
其他使用方法
因为官方文档中只是没有说明要如何将vuex引入到项目中, 因此也就不记录其他例如mutations
的用法的, 感兴趣的可以自行查看官方文档.
参考
- Post title:vue项目中使用vuex存储变量
- Post author:QBug
- Create time:2021-05-15 11:37:58
- Post link:https://q-bug4.github.io//articles/2021/05/15/1621049877913.html
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.