2016-12-02 10 views
0

私は、私が望むときにプログラムで挿入できるようにしたいモーダルコンポーネントを持っています。 Vueでこれを行う方法がありますか?例えばVue jsはプログラムでコンポーネントを作成します

Vue.component('login', { 
    methods: { 
    openLoginModal() { 
     // Create the component modal and pass the props 
    } 
    } 

}); 

:私はモーダルテンプレートはなりたくない、私はこのような何かを行うことができるようにしたい任意のコンポーネントで次に

Vue.component('modal', {...}) 

私はモーダルを使用する必要があるすべてのコンポーネントで。 bodyタグにモーダルコンポーネントを追加するだけです。

答えて

0

これを行う最もクリーンな方法は、vuex経由で終了すると思います。

あなたはbodyタグの前に言うようにそのため、あなたが、あなたのアプリケーションのルート内のモーダル・コンポーネントを設定したい:

<div id="app"> 

    ... 

    <modal v-if"showModal" inline-template> 
     <div v-html="modalContent"></div> 
    </modal> 

</div> 
</body> 

を今、あなたは私と一緒にモーダルを切り替えることができるようになりますvuexストアを作成それはコンテンツだ取り込む前提としています

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

Vue.use(Vuex) 

new Vuex.Store({ 
    state: { 
     showModal: false, 
     modalContent: '', 
    }, 
    mutations: { 
     toggleModal: (state) => { 
      state.showModal = !state.showModal 
     }, 
     setModalContent: (state, content) => { 
      state.modalContent = content 
     }, 
    }, 
}) 

(あなたのアプリケーションのルート用のテンプレートは、モーダル・コンポーネントが含まれているとして)自分のアプリで店を登録し、showModalのための計算された小道具を設定します。

export default { 

    computed: { 
     modalContent() { 
      return this.$store.state.modalContent 
     }, 
     ... 

モーダル・コンポーネントは、今あなたがにアプリ全体で任意のコンポーネントからvuexストア変異を呼び出すことができます。少なくともstate.modalContentの値を見るにモーダルコンポーネントを設定

import store from './vuex/store' new Vue({ el: '#app', store, computed: { showModal() { return store.state.showModal }, ... }) 

その内容を更新し、可視性を切り替える:

例コンポーネント

export default { 

    mounted() { 

     this.$store.commmit('setModalContent', '<h1>hello world</h1>') 

     this.$store.commmit('toggleModal') 
     ... 
関連する問題