movii
7/25/2017 - 9:12 AM

笔记:Vue.js 中使用 Vuex 的一个例子 - 3. passing data with Vuex

笔记:Vue.js 中使用 Vuex 的一个例子 - 3. passing data with Vuex

// <App> component as wrapper
const App = new Vue({
  el: '#app',
  components: {
    Parent, 
    Child
  },
  store,
  data () {
    return { AppMessage: `This message is from App.vue` };
  },
  computed: {
    message () {
      return `result: ${this.AppMessage} + ${this.$store.state.message}`
    }
  }
});
// <child> component
const Child = Vue.component('child', {
  template: `
    <div class="box box-child">
      <h1>{{ message }}</h1>
      <button @click='$store.dispatch( "changeMessage", "message from <child>")'>change message from &lt;child&gt;</button>
    </div>
  `,
  computed: {
    message () {
      return this.$store.state.message;
    }
  }
});
// <parent> component
const Parent = Vue.component('parent', {
  template: `
    <div class="box box-parent">
      <h1>{{ message }}</h1>
      <button @click='$store.dispatch( "changeMessage", "message from <parent>")'>change message from &lt;parent&gt;</button>
      <slot></slot>
    </div>
  `,
  computed: {
    message () {
      return this.$store.state.message;
    }
  }
});
// Vuex.Store 
const store = new Vuex.Store({
  state: {
    message: 'This message is from $store'
  },
  mutations: {
    updateMsg (state, message) {
      state.message = message;
    }
  }, 
  actions: {
    changeMessage (context, message) {
      context.commit('updateMsg', message);
    }
  }
});