2016-12-26 84 views
1

我從VUE-MDL如何通過單擊Vue.js調用組件上的方法?

<template> 
<div class="mdl-dialog-container" v-show="show"> 
    <div class="mdl-dialog"> 
    <div class="mdl-dialog__title">{{title}}</div> 
    <div class="mdl-dialog__content"> 
     <slot></slot> 
    </div> 
    <div class="mdl-dialog__actions" :class="actionsClasses"> 
     <slot name="actions"> 
     <mdl-button class="mdl-js-ripple-effect" @click.native.stop="close">Close</mdl-button> 
     </slot> 
    </div> 
    </div> 
</div> 
</template> 

<script> 
import mdlButton from './button.vue' 
import createFocusTrap from 'focus-trap' 

export default { 
    components: { 
    mdlButton 
    }, 

    computed: { 
    actionsClasses() { 
     return { 
     'mdl-dialog__actions--full-width': this.fullWidth 
     } 
    } 
    }, 

    data() { 
    return { 
     show: false 
    } 
    }, 

    props: { 
    title: { 
     type: String 
    }, 
    fullWidth: Boolean 
    }, 

    mounted() { 
    this._focusTrap = createFocusTrap(this.$el) 
    }, 

    methods: { 
    open() { 
     this.show = true 
     this.$nextTick(() => this._focusTrap.activate()) 
     this.$emit('open') 
    }, 
    close() { 
     this.show = false 
     this._focusTrap.deactivate() 
     this.$emit('close') 
    } 
    } 
} 
</script> 

使用對話框窗口dialog.vue的成分我要帶上一個對話窗口,其他組件

<mdl-dialog></mdl-dialog> 
<button class="mdl-button mdl-js-button mdl-button--raised">Click me</button> 

我沒有發現有關如何調用另一個組件的方法的信息。所有的例子主要是用道具。告訴我該怎麼做?

如何才能調用方法open() in <mdl-dialog></mdl-dialog>

回答

1

因爲他們不是父母的孩子,所以你想使用一個事件總線。由於您使用的.vue文件,你可以創建一個名爲bus.js文件中像

import Vue from 'vue' 
export default new Vue() 

然後,進口的是你需要的地方發出,並聽取了集中的事件。這裏有一個簡單的例子:

// SomeComponent.vue 
import bus from './bus.js' 

export default { 
    methods: { 
    log (msg) { 
     console.log(msg) 
    } 
    }, 
    created() { 
    bus.$on('someEvent', this.log) 
    } 
} 

然後在另一個組件,你可以這樣做......

// AnotherComponent.vue 
import bus from './bus.js' 

export default { 
    methods: { 
    emitClick (msg) { 
     bus.$emit('Hello from AnotherComponent.vue') 
    }, 
    }, 
} 

你可以閱讀了一點更多關於它在這裏:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

+1

如何使用公交車在MDL-按鈕,如果我把它通過NPM?爲什麼然後需要一個方法open(),如果我不在任何地方調用這個方法? – LANSELOT

0

你可以在下方創建輔助方法在你的父組件中的方法:

getChild(name) { 
    for(let child of this.$children) if (child.$options.name==name) return child; 
}, 

並調用子組件方法是這樣的:

this.getChild('mdl-dialog').open(); 

我沒有測試它的Vue公司> = 2.0