19 Vuex数据共享
1、全局注册Vuex并抛出Vuex下的Store
import Vue from 'vue' import Vuex from 'vuex' //全局Vue注册Vuex Vue.use(Vuex); //抛出Vuex.Store对象 export default new Vuex.Store({ state: { count: 1 }, //只能做同步操作,不要做异步操作 mutations: { addCount(state, value) { //这个默认的state是上面的state对象 state.count += value } }, //可做异步操作,也可做同步操作,action提交的也是mutation actions: { sync(context, value) { context.commit("addCount", value) }, async(context, value) { //2秒后加相应值 setTimeout(() => { context.commit("addCount", value) }, 2000) } } });
2、main.js中导入store,并添加到Vue实例中
3、在组件1中通过计算属性监听
<template> <div id="app"> 父组件Count:{{count}} <SubCom/> </div> </template> <script> import SubCom from './components/SubCom' export default { name: 'App', components: { SubCom }, computed:{ count(){ return this.$store.state.count } } } </script>
4、在组件2中同样监听,并给定修改方法,方法内部 使用dispatch来提交
<template> <div class="hello"> 子组件{{count}} <br> <button @click="Async">点我异步加10(2秒后)</button> <button @click="Sync">点我同步加5</button> </div> </template> <script> export default { name: 'SubCom', data() { return { msg: 'Welcome to Your Vue.js App' } }, computed: { count() { return this.$store.state.count } }, methods: { Sync() { this.$store.dispatch('sync', 5) }, Async() { this.$store.dispatch("async", 10) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>