0

我试图让一个简单的子组件将一个事件传递给它的父级,但它没有被调用。

不知道还能尝试什么,正在调用 Widget 的点击事件,但没有将其发送给它的父级,因为它没有调用 console.log

我在这里想念什么?

父.vue:

<template>
    <Page class="page">
        <ActionBar title="Home" class="action-bar" />
        <ScrollView>
            <StackLayout class="home-panel">
                <Widget v-for="widget in widgets" :widgetName="widget.name"/>
                <Button text="Add widget" class="btn btn-primary" @tap="addWidget" />
            </StackLayout>
        </ScrollView>
    </Page>
</template>

<script>
    import Widget from "./Widget";
    export default {
        data() {
            return {
                widgets: [{
                    name: "widget1"
                }, {
                    name: "widget2"
                }]
            };
        },
        components: {
            Widget
        },
        methods: {
            addWidget() {
                this.widgets.push(
                    {
                        name: `widget${this.widgets.length+1}`
                    }
                )
            },
            removeWidget(name){
                console.log('removing widget');
                this.widgets.forEach( (i, widget) => {
                    if(widget.name === name){
                        this.widgets.splice(i,1);
                    }
                })
            }
        }
    };
</script>

小部件.vue:

<template>
    <Button :text="widgetName" @tap="removeThis">
</template>

<script>
    export default {
        props: {
            widgetName: "",
        },
        methods: {
            removeThis(){
                console.log('emiting event to remove widget', this.widgetName);
                this.$emit("removeWidget", this.widgetName);
            }
        }
    };
</script>

我是 vue 和 nativescript 的真正初学者。

游乐场示例:https ://play.nativescript.org/?template=play-vue&id=9dPpDZ&v=3

4

2 回答 2

2

您的代码中缺少两件事,

首先,您假设处理来自父组件的发出事件

<Widget v-for="widget in widgets" :widgetName="widget.name"
                @removeWidget="removeWidget" />

其次,你的forEach语法,回调的第一个参数是widget,第二个参数是索引(i),

this.widgets.forEach((widget, i) => {
                if (widget.name === name) {
                    this.widgets.splice(i, 1);
                }
            });

更新游乐场

于 2018-11-22T19:53:29.403 回答
2

You have to handle the emitted event in the parent component like :

    ....
  <Widget v-for="widget in widgets" :widgetName="widget.name"  @remove-widget="removeWidget" />
    ...

and add the method removeWidget as follows :

     methods: {
        addWidget() {
            ....
           },
         removeWidget(name){
             console.log('removing widget');
            this.widgets.forEach( (widget,i ) => {
                if(widget.name === name){
                    this.widgets.splice(i,1);
                }
            })
          }
        }
于 2018-11-22T19:47:15.783 回答