Vue

by hinablue

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.min.js"></script>
<div id="app">
  <h1>Action: <span v-text="action"></span></h1>
  <p v-show="action === 1">
    Doing something...
  </p>
  <p v-show="doOther">
    Do other thing...
  </p>
  <p>
    <span>Watch running:</span>
    <span v-text="watchRunning"></span>
  </p>
  <br>
  <button type="button" @click.stop="callAction">
    Call Action
  </button>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

Vue

var store = new Vuex.Store({
  state: {
    userState: 0
  },
  getters: {
    getUserState: function(state) {
      return state.userState
    }
  },
  mutations: {
    updateUserState: function(state, data) {
    	state.userState = data
    }
  },
  actions: {
    changeUserState: function(context) {
      context.commit('updateUserState', 1)
    }
  }
})

new Vue({
  el: "#app",
  store: store,
  data: {
    doOther: false,
    watchRunning: ''
  },
  computed: {
    action: function() {
      return this.$store.getters.getUserState
    }
  },
  methods: {
  	callAction: function() {
      this.$store.commit('updateUserState', 0)
      this.$store.dispatch('changeUserState')
    },
    doOtherThings: function() {
      var self = this
      this.doOther = true
      setTimeout(function() {
        // Wait 1 second.
        self.doOther = false
      }, 1000)
    }
  },
  created () {
    var self = this
    this.$watch(function() {
      return self.action
    }, function(newAction) {
      self.watchRunning += '' + newAction
      if (newAction === 1) {
        self.doOtherThings()
      }      
    }, {
      sync: true
    })
  }
})