【问题标题】:VueJS: Passing child method to parent doesn't executeVueJS:将子方法传递给父级不执行
【发布时间】:2019-07-31 07:35:10
【问题描述】:

在这里,父母将nameage 道具传递给孩子。子组件发出一个自定义事件changeAgeFn,将其changeAge 方法传递给父组件。

在父级中,(通过)changeAge 事件附加到button[change age] 上的单击事件。

但是这种方式行不通。我想知道从父级执行子事件的标准/推荐方式。

Parent.vue

<template>
    <div class="parent-wrap">
        <p>UserName: {{user}}, age: {{age}}
        <button @click="changeAge()"> Change Age</button></p>
        <child :user="user" :age="age" @userChanged="user = $event" @changeAgeFn="$event" ></child>
    </div>
</template>

<script>
    import child from './child.vue'

    export default {
        data: function() {
            return {
                user: 'John',
                age: 35
            }
        },
        components: {
            child
        },        
    }
</script>

<style>
.child-wrap {
  border: 3px solid #000;
  max-width: 300px;
  padding: 20px;
  background: lightblue;
}

.parent-wrap {
  padding: 30px;
  background-color: lightcoral;
  border: 3px solid #000;
}
</style>

child.vue

<template>
    <div class="child-wrap">
        <p>UserName: {{user}}, age: {{age}}
        <button @click="changeName"> Change Name</button></p>
    </div>
</template> 

<script>
    export default {
        props: ['user', 'age'],
        methods: {
            changeName() {
                this.user = 'Rahul'
                this.$emit('userChanged', this.user)
                this.$emit('changeAgeFn', this.changeAge)
            },
            changeAge() {
                this.age = '20'
            }
        }
    }
</script>

谢谢

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我认为您在这里有点困惑。您需要将 changeAge 作为 prop 从父组件注入到子组件,以便它更新父组件的状态并触发子组件的重新渲染。

    所以你的孩子需要一个带有以下签名的道具:

    changeAge: () => void
    

    然后在父级中定义 changeAge:

    // parent, NOT child 
    methods: {
        ...
        changeAge() {
                this.age = '20'
            }
    ...
    

    }

    然后将其注入孩子:

    <template>
        ...
        <child :changeAge=“changeAge” etc.../>
        ...
    </template>
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 1970-01-01
      • 2019-04-19
      • 2013-02-28
      • 2017-01-07
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多