簡體   English   中英

VueJS 中的父子通信

[英]Parent-child communication in VueJS

我有兩個 Vue 組件。 parent-component

Vue.component('parent-component',{
        methods: {
            test: function(){
             alert('Option Selected');
            }
        },
        template: `
            <div><slot></slot></div>
        `
});

animals部分:

Vue.component('animals',{
        data: function(){
            return {
                selected: ''
            }
        },
        template: `
            <select @change="selectionChanged" v-model="selected">
                <slot></slot>
            </select>
        `,
        methods: {
            selectionChanged: function(){
                this.$emit('optionselected', this.selected);
            }
        }
 });

這是我的 HTML:

<div id="app">
        <parent-component @optionselected="test()">
            <animals>
                <option>Aardvark</option>
                <option>Bear</option>
                <option>Cat</option>
            </animals>
        </parent-component>
 </div>

我正在嘗試將所選選項從子組件( animals )獲取到父組件( parent-component )。 我正在從子組件發出optionselected事件,但看起來父組件沒有響應該事件,我的意思是根本沒有調用 test() 方法。 我在這里做錯了什么?

這是JSFiddle 演示

首先,您需要將偵聽器添加到模板中的animals組件。

<animals @optionselected="test">

其次,重要的是要記住,因為您使用的是插槽,所以插槽內的元素將在定義它們的組件范圍內進行評估。 在這種情況下,該范圍是 Vue 的范圍,而不是parent-component范圍。 為了允許定義在槽內的元素使用包含的組件數據、方法等,您需要定義一個作用域槽 在這種情況下,您的父組件最終將如下所示:

<div><slot :test="test"></slot></div>

你的 Vue 模板變成

<parent-component>
  <template scope="{test}">
    <animals @optionselected="test">
      <option>Aardvark</option>
      <option>Bear</option>
      <option>Cat</option>
    </animals>
  </template>
</parent-component>

這是更新的代碼。

 console.clear() Vue.component('parent-component', { methods: { test: function(option) { alert('Option Selected ' + option); } }, template: ` <div><slot :test="test"></slot></div> ` }); Vue.component('animals', { data: function() { return { selected: '' } }, template: ` <select @change="selectionChanged" v-model="selected"> <slot></slot> </select> `, methods: { selectionChanged: function() { this.$emit('optionselected', this.selected); } } }); new Vue({ el: "#app", });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> <div id="app"> <parent-component> <template scope="{test}"> <animals @optionselected="test"> <option>Aardvark</option> <option>Bear</option> <option>Cat</option> </animals> </template> </parent-component> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM