The usage of $emit and props in vue

1. The parent component uses props to pass data to the child component
2. The child component uses $emit to trigger a custom event of the parent component

Child component: child.vue

<template>
  <div class="child">
    <h3>接收父组件传递过来的值:{
   
   {sendData}}</h3> 
    <br/>
    <button @click='toParent'>点击将子组件内容传递给父组件</button>
  </div>
</template>
<script>
  export default {
    props:['sendData'], 
    methods:{
      toParent() {
        this.$emit('showData',"通过$emit传递给父组件");//toParent事件触发后,自动触发showData事件
      }
    }
  }
</script>

 Parent component: parent.vue

<template>
    <div class="parent">
      <p>{
   
   {childData}}</p>
      <Child @showData="updateData" :sendData="childData"></Child>
    </div>
</template>
<script>
  import Child from "./child";
  export default {
    components: {Child},
    data(){
        return {
            childData:"父组件传递给子组件的值"
        }
    },
    methods:{
      //通过触发子组件触发,修改父组件定义的值
      updateData(data){
       this.childData=data;
      }
    }
  }
</script>

 

Guess you like

Origin blog.csdn.net/SmartJunTao/article/details/108471728