0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vuexを使わないで共通状態管理を行う

0
Last updated at Posted at 2019-05-15

そもそも共通状態管理はどういう時に使うの?

・複数の画面で同じ値を使いたい時。
・URLに値載せたくないけど遷移先で値使いたい時。
参考:
https://stackoverflow.com/questions/40774131/hide-query-params-in-address-bar-vuejs
・そのほか使いたいと思う時がある時。

なぜVuexや自作のもので共通状態管理をおこなうの?データから直で値持って来ちゃダメなの?

変えたのがコード上でしかわからないのでこんがらがるなどの理由があります。
値変更時にログ出力しとけば『あ~そこでその値変えたのね!!』とかなってバグ修正がしやすくなる。『あ!ここで共通の値かえてる〜、だからおかしかったんだ!』とかとか。

もっと詳しく説明してくれていると思った参考以下
https://vuex.vuejs.org/ja/

で?? 実際コードどんな感じなの?

ちなみに参考お手本以下URL
https://jp.vuejs.org/v2/guide/state-management.html

大元のところ

main.js
var store = {
  debug: true,
  state: {
    message: 'Hello!'
  },
  setMessageAction(newValue) {
    if (this.debug) console.log('setMessageAction triggered with', newValue)
    this.state.message = newValue
  },
  clearMessageAction() {
    if (this.debug) console.log('clearMessageAction triggered')
    this.state.message = ''
  }
}


new Vue({
  data: {
    privateState: store.state
    // sharedState: store.state
  },
  methods: {
    setMessageAction: function(newValue) {
      store.setMessageAction(newValue)
    },
    clearMessageAction: function() {
      store.clearMessageAction()
    }
  },
  render: h => h(App),
}).$mount('#app')

使用方法

console.log(this.$root.$data.privateState.message);
とか
<div>{{this.$root.$data.privateState.message}}</div>
とか
this.$root.setMessageAction('変更したよ!');
とか

コードの説明

main.js
new Vue({
  data: {
    privateState

のところの

main.js
privateState

main.js
this.$root.$data.privateState

で呼べてる。

main.js
new Vue({
  data: {
    privateState: store.state
    // sharedState: store.state
  },
  methods: {
    setMessageAction: function(newValue) {
      store.setMessageAction(newValue)

main.js
setMessageAction: function(newValue)

のところが

main.js
this.$root.setMessageAction('変更したよ!');

で呼べてる。

さいごにここの説明を

main.js
if (this.debug) console.log('setMessageAction triggered with', newValue)
    this.state.message = newValue

もし、debugをtrueにしていたらログをだします。
自分のもってるmessageを新しい値にかえます。

これはやっちゃだめ

ログ出力しないので、せっかく作ったの意味なくなる
this.$root.$data.privateState.message = '変わりました!';

最後に

間違っている部分などあれば教えていただけると嬉しいです!

参考:
https://qiita.com/residenti/items/550589313cfef43062c3

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?