繁体   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