vue父子组件通信

父组件传递数据msg给子组件

父组件: 在子组件上通过绑定:childmsg="msg" 来传递给子组件

<template>
  <div id="father">
    <div class="el-lab">父传子:</div>
    <input  placeholder="向子组件传递数据" v-model="msg"/>
  </div>

  <Child :childmsg="msg" ></Child>
</div>
</template>

<script>
import Child from './child1.vue'
  export default {
    data(){
      return {
        msg: '从父组件过来的数据',
      }
    },
    components: { Child },
  }
</script>

子组件接收父组件传过来的msg

子组件:通过props:['childmsg']的方式来接收

<template>
  <div id="child1">
    <h4>子组件1</h4>
    <p>接收父穿过来的数据:{{childmsg}}</p>
  </div>
</template>

<script>
export default {
  props: ['childmsg'],
  data(){
    return {
    }
  },
}
</script>

子组件传递数据给父组件

子组件:通过this.$emit('sendTo',this.msg)创建一个sendTo的响应方式

<template>
  <div id="child1">
    <div class="box">
    <h4>子组件</h4>
    <div class="input-1">
      <div class="el-lab">子传父:</div>
      <input class="ch-in" placeholder="向父组件传递数据" v-model="msg" @keyup="tofa" />
    </div>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      msg: '',
    }
  },
  mounted(){
  },
  methods: {
    tofa(){
      this.$emit('sendTo',this.msg)
    }
  }
}
</script>

父组件接收子组件传过来的msg

父组件:在子组件上绑定@sendTo=getMsg来接收子组件传递过来的msg并赋给父组件的msg

<template>
  <div id="father">
    <div class="input-1">
      <div class="el-lab">接收子:{{msg}}</div>
    </div>
  <Child  @sendTo="getMsg"></Child>
</div>
</template>

<script>
  import Child from './child1.vue'
  export default {
    data(){
      return {
        msg: '',
      }
    },
    components: { ChildOne },
    mounted(){

    },
    methods: {
      getMsg(msg){
        this.msg = msg
      }
    }
  }
</script>

猜你喜欢

转载自www.cnblogs.com/hopesthwell/p/9207121.html