1

VueJs + VueX を使用して SPA を構築し、1 つのコンポーネントで「ログイン」ボタンと「サインアップ」ボタンをクリックし、<component></component>条件付きでレンダリングする必要がある他のコンポーネントにタグを付けます (「サインアップ」フォームと「ログイン フォーム」)。 . モーダルもコンポーネントです。
console.log を呼び出すと、クリックしたボタンに応じて state.currentView が変化することがわかりますが、{{ $data | マークアップ内の json }} は、状態が変更されていないことを示しており、さらに重要なのはモーダルが変更されていないことです。だから私は次のようにコードを書いた:

App.vue:

<template>
  <navbar></navbar>
  <component v-bind:is="currentView"></component>
</template>

<script>
 import Login from './components/Login'
 import Signup from './components/Signup'
 import Navbar from './components/Navbar'
 import NavbarInner from './components/NavbarInner'

 import store from './vuex/store'

 export default {
 name: 'app',
 data () {
   return {
     currentView: this.$store.state.currentView
   }
 },
 components: {
   Login,
   Signup,
   Navbar,
 },
 store
}
</script>

Navbar.vue テンプレートでは、currentView の状態を変更するためのボタンとメソッドを保持しています。

    <md-button class="navbar__link"
               @click="changeCurrentModal('Signup')">
      Sign Up
    </md-button>

    <md-button class="navbar__link"
               @click="changeCurrentModal('Login')">
      Login
    </md-button>

    export default {
     name: 'navbar',
     computed: {
       currentView () {
        return this.$store.state.currentView
      }
    },
    methods: {
      changeCurrentModal (curentView) {
        this.$store.commit('changeCurrentModal', curentView)
     }
   }
 }
 </script>

私の store.js ファイルは次のようになります。

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
  currentView: 'Signup'
},
mutations: {
  changeCurrentModal: (state, currentView) => {
    console.log(currentView)
    state.currentView = currentView
  }
},
actions: {
   changeCurrentModal: ({commit}, currentView) => {
     commit('changeCurrentModal', currentView)
   }
  } 
})
4

2 に答える 2

1

すべきことは、ゲッターを作成し、計算されたプロパティを使用してコンポーネントにプルすることです。

あなたのビューは...

...

export default new Vuex.Store({
   state: {
      currentView: 'Signup'
   },
   getters: {
      getCurrentView: state => {
          return state.currentView
      }
   }
   mutations: {
      ...
   },
   actions: {
      ...
   }
})

そして、計算されたプロップは次のようになります...

computed: {
  currentView () {
    return this.$store.getters.getCurrentView
  }
}

これにより、vuex データとの反応性が維持されます。

于 2016-11-23T16:08:53.850 に答える
0

Vuex が動作するようになりましたが、まだチェックしていない場合は、Vue-router をチェックしてみてください。それはあなたが望むのと同じことを達成し、従うのがより簡単なコードを提供するかもしれません.

于 2016-11-02T03:01:23.597 に答える