vuex简单的案例
vuex
-
作用:实现全局数据共享
-
使用:
-
安装 Vuex
npm install vuex --save
-
注册到vue项目
import Vue from 'vue' import App from './App' import router from './router' import store from './store/index.js' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
-
定义Vuex文件
store/index.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 } })
-
组件中访问
count
this.$store.state.count
-
组件中更改
count
需要在store/index.js
中添加mutations
const store = new Vuex.Store({ state:{ count:0 }, mutations:{ add(state){ state.count ++ } } })
-
组件中更改数据
methods:{ // 第一种方法 三个点的意思是扩展运算符 提取并打开 ...mapMutations(['add']) // 第二种方法 this.$store.commit('add') }
-
如果需要异步改写数据 则需要借助
actions
const store = new Vuex.Store({ state:{ count:0 }, mutations:{ add(state){ state.count ++ } }, actions:{ addasync(complex){ setTimeout(()=>{ complex.commit('add') },1000) } } })
-
组件中需要异步改变数据
methods:{ // 第一种方法 三个点的意思是扩展运算符 提取并打开 ...mapActions(['addasync']) // 第二种方法 this.$store.dispatch('add') }
-
mapActions 和 mapMutations 是 vuex 提供的两个辅助函数
import { mapMutations,mapActions } from 'vuex'
-
完整的示例
// main.js import Vue from 'vue' import App from './App' import router from './router' import store from './store/index.js' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
// store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state:{ count:0 }, mutations:{ add(state){ state.count ++ } }, actions:{ addasync(complex){ setTimeout(()=>{ complex.commit('add') },1000) } } }) export default store
// demo.vue <template> <div> <span>{{count}}</span> <button @click="add">+</button> <button @click="addasync">+async</button> </div> </template> <script> import { mapMutations,mapActions } from 'vuex' export default { data () { return { } }, computed: { count: function () { return this.$store.state.count; } }, methods:{ ...mapMutations(['add']), ...mapActions(['addasync']) } } </script>
-
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!