手记

vue中父子组件相互协作传递数据

子组件代码

<template>
  <div class="my-header">
    公共头部
    <p @click="emitMyEvent">{{numberToDo}}</p>
  </div>
</template>

<script>
  export default {
    name: 'my-header',
    //父组件传过来的值(此处已经将numberToDo 绑定到 此组件的data下)
    //  props: ['number-to-do'],
    //用对象类型的可以限定传过来的值的类型
    props: {
      'number-to-do': 'Number'
    },
    data () {
      return {
        msg: 'Welcome to My header'
      }
    },
    methods: {
      emitMyEvent: function () {
        //自定义事件 父组件可以使用<my-header  @my-event="indexeEmitMyEvent"></my-header>
        //后面的this.msg是给父组件传递的参数
        this.$emit('my-event', this.msg);
      }
    }
  }
</script>

父组件代码

<template>
  <div class="index">
    <input type="text" v-model="myVal">
    <my-header :number-to-do="myVal" @my-event="indexeEmitMyEvent"></my-header>
  </div>
</template>

<script>
  import MyHeader from './common/MyHeader.vue'
  export default {
    name: 'index',
    components: {MyHeader},
    data () {
      return {
        msg: 'Welcome to Your Vue.js App',
        myVal: "1111"
      }
    },
    methods: {
      indexeEmitMyEvent: function (val) {
        console.log("子组件传过来的值:", val)
      }
    }
  }
</script>
0人推荐
随时随地看视频
慕课网APP