组件通讯
1、文件存放
└── store
├── index.js # 我们组装模块并导出 store 的地方
└── modules
├── demo1.js # 模块1
└── demo2.js # 模块2
2、main.js存放的内容
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
window.EventBus = new Vue();
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3、idex.js存放的内容
import Vue from 'vue'
import Vuex from 'vuex'
import demo1 from './modules/demo1'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
demo1,
},
})
4、demo1.js存放的内容
let user = {
// 状态state用于存储所有组件的数据。
state: {
text: "我是字符串",
bool: true,
},
// .getters:计算属性,对state里的变量进行过滤
getters: {
text123: function (state) {
return state.text + '123456';
}
},
// mutations:唯一可以改变state数据的工具,相当于vue里的methods
mutations: {
SET_TEXT: (state, text) => {
state.text = text;
},
},
// 异步操作
// 只能调用mutations,不能直接修改state
actions: {
SET_TEXT: (state, text) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
state.commit("SET_TEXT", text);//修改了cartNum的值为1
resolve()
}, 3000)
})
},
},
}
export default user
5、使用(不使用辅助函数)
<script>
export default {
components: {
},
computed: {
},
async mounted() {
console.log(this.$store.state.demo1.text);
console.log(this.$store.getters.text123);
this.$store.commit("SET_TEXT", "wwwwwwwww");
console.log(this.$store.state.demo1.text);
console.log(this.$store.getters.text123);
// this.$store.dispatch("SET_TEXT", "xxxxxxxxxxxx").then(() => {
// console.log(this.$store.state.demo1.text);
// console.log(this.$store.getters.text123);
// });
await this.$store.dispatch("SET_TEXT", "xxxxxxxxxxxx");
console.log(this.$store.state.demo1.text);
console.log(this.$store.getters.text123);
},
methods: {
},
};
</script>
6、使用(使用辅助函数)
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
components: {
},
computed: {
...mapState(["demo1"]),
...mapGetters(["text123"]),
},
methods: {
...mapActions(["SET_TEXT"]),
...mapMutations({ SET_TEXT_123: "SET_TEXT" }),
},
async mounted() {
console.log(this.demo1.text);
console.log(this.text123);
this.SET_TEXT_123("wwwwwwwww");
console.log(this.demo1.text);
console.log(this.text123);
// this.$store.dispatch("SET_TEXT", "xxxxxxxxxxxx").then(() => {
// console.log(this.demo1.text);
// console.log(this.text123);
// });
await this.$store.dispatch("SET_TEXT", "xxxxxxxxxxxx");
console.log(this.demo1.text);
console.log(this.text123);
},
};
</script>