【转载】Vue 关于 $emit 与 props 的使用

转自:https://blog.csdn.net/m0_56388720/article/details/123067654

props 和 $emit

  • 子组件向父组件传值,通过$emit 事件向父组件发送消息,将自己的数据传递给父组件。

  • props 可以在组件上注册一些自定义属性。父组件通过绑定该属性来向子组件传入数据,子组件通过 props 属性获取对应数据。

示例

父组件

// parent.vue
<template>
    <div>
        <p>childMessage: {{childMessage}}</p>
        <children :sendmessage='childMessage' @showMsg="updataMsg"></children>
    </div>
</template>

import children from '/*...*/'

export default{
    data () {
        return {
            childMessage: '父组件给子组件传值'
        }
    },
    methods: {
        updataMsg(message) {
            this.childMessage = message
            console.log(this.childMessage)
        }
    },
    components: {
        children
    }
}

子组件

// children.vue
<template>
    <div>
        // 通过按钮点击事件将子组件的值传给父组件
        <button @click="sendtoParent">Click this Button</button>
    </div>
</template>

<script>

export default {
  props: ['sendmessage'],
  methods: {
    sendtoParent() {
        //$emit括号里的第一个参数为自定义事件
        this.$emit('showMsg','子组件通过$emit给父组件传值')
    }
  }
}
</script>
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注