No more IE!請試著使用FirefoxGoogle Chrome等瀏覽器瀏覽
標頭的可愛Alaskan Malamute來自維基百科~

2017年5月8日 星期一

Vue.js: How to watch a shared state

Using Vue, we can store states outside instances for better management, like this:
HTML:
<div id="a" v-show="managedState.showA">This is A</div>
<div id="b" v-show="managedState.showB">This is B</div>
JavaScript:
var stateManager = {
  states: {
    showA: true,
    showB: false,
  },
  whichOn: 'showA',
  toggle: function (opt) {
    if (!this.states.hasOwnProperty(opt)) {
      console.log('Error');
      return;
    }
    this.states[this.whichOn] = false;
    this.states[opt] = true;
    this.whichOn = opt;
  }
};

new Vue({
  el: '#a',
  data: {
    managedState: stateManager.states
  }
});
new Vue({
  el: '#b',
  data: {
    managedState: stateManager.states
  }
});
With above settings, this code works fine:
JavaScript:
stateManager.toggle('showB');

Nice, but somehow if you needs to "watch" on just one of these shared states, you can watch on a "Computed Property" instead.
Rewrite these Vue instances (not a good case, just for example):
JavaScript:
new Vue({
  el: '#a',
  data: {
    managedState: stateManager.states
  },
  computed: {
    show: function () {
      return this.managedState.showA;
    }
  },
  watch: {
    show: function () {
      if (this.show) document.body.style.backgroundColor = 'lightblue';
    }
  }
});
new Vue({
  el: '#b',
  data: {
    managedState: stateManager.states
  },
  computed: {
    show: function () {
      return this.managedState.showB;
    }
  },
  watch: {
    show: function () {
      if (this.show) document.body.style.backgroundColor = 'pink';
    }
  }
});

Now, the background color of body will change after you call stateManager.toggle accordingly.