vuex实现数据共享
2024-09-01 09:33:15
1.store.js结构
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({
state: {
city: '汉中'
},
mutations: { },
actions: { }
})
2.main.js引入
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3.组件使用State的数据
{{ this.$store.state.city }}
4.用dispatch调用Actions,Actions用commit调用Mutations修改数据
具体组件.vue
methods: {
handleClick (city) {
this.$store.dispatch('changeCity', city)
}
}
store.js
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({
state: {
city: '汉中'
},
mutations: {
changeCity (state, city) {
state.city = city
}
},
actions: {
changeCity (ctx, city) {
// ctx为上下文,city是传来的参数
ctx.commit('changeCity', city)
}
}
})
5.数据简单,跳过Actions,直接到Mutations
具体组件.vue
methods: {
handleClick (city) {
this.$store.commit('changeCity', city)
}
}
store.js
import Vue from 'vue'
import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({
state: {
city: '汉中'
},
mutations: {
changeCity (state, city) {
state.city = city
}
}
})
最新文章
- MFC 关于MFC中CImage的简单使用
- angular 自定义指令 link
- MVC缓存技术
- TF-IDF算法扫盲2
- bzoj4046
- uva 10651 - Pebble Solitaire(记忆化搜索)
- 【Python网络爬虫四】通过关键字爬取多张百度图片的图片
- 安装ARM交叉编译器
- JBoss7 如何用脚本 启动 和 停止
- Linux学习历程——Centos 7 chmod命令
- Python基础之函数参数
- ComboBox下拉列表框
- mycat 测试主从读写分离
- XML异常
- centos7如何查看网络状态?
- hdu 2844 coins(多重背包 二进制拆分法)
- How to use Jackson to deserialise an array of objects
- basename 命令
- Azure SQL 数据库仓库Data Warehouse (3) DWU
- vc 读xml文件 宏