【Vue】 vue2.0父子组件传递函数

这篇博客主要介绍了在Vue2.0中如何实现父组件向子组件传递函数的方法,包括通过props和$emit的方式。作者分享了自己的学习心得,并期待社区的反馈和指正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习笔记:在vue2.0中,父组件调用子组件时,想要将父组件中的函数体也做传递

1. 通过props :需要从子组件传参数到父组件时适用

// 父组件.vue

<template>
  <div>
    <ok-input :params='number' :callback='callbackNum'></ok-input>
  </div>
</template>
<script type="text/ecmascript-6">
  import okInput from '../ok-input/okinput.vue';
  export default {
    props: {},
    data() {
      return {
        number: {},
        callbackNum: function (x) {
          console.log(x);
        }
      };
    },
    methods: {
    },
    components: {
      'ok-input': okInput
    }
  };
</script>
// 子组件.vue
<template>
  <div>
      <input v-model='numVal' @change='handleFun'></input>
  </div>
</template>
<script type="text/ecmascript-6">
  import {Input, Select, Option, Button} from 'element-ui';
  import 'element-ui/lib/theme-default/index.css';
  export default {
    props: {
      params: {
        type: Object,
        default: {
          type: ''
        }
      },
      callback: {}
    },
    data() {
      return {
        x: 'hah',    
        numVal: ''
      };
    },
    methods: {
      handleFun(val) {
          this.callback(val); // 将参数传回父组件中的回调函数
      }
    },
    components: {
      'el-input': Input,
    }
  };
</script>

2.通过$emit: 只需获得当前操作对象时适用

// 父组件.vue

<template>
  <div>
    <ok-input :params='inputs' @change='handleAge'></ok-input>
  </div>
</template>
<script type="text/ecmascript-6">
  import okInput from '../ok-input/okinput.vue';
  export default {
    props: {},
    data() {
      return {
        number: {}
      };
    },
    methods: {
      handleAge(evt) {
        console.log(evt.target.value); // 接收从子组件传过来的当前对象
      }
    },
    components: {
      'ok-input': okInput
    }
  };
</script>
// 子组件.vue
<template>
  <div>
      <input v-model='numVal' @blur='handleChange'></input>
  </div>
</template>
<script type="text/ecmascript-6">
  import {Input, Select, Option, Button} from 'element-ui';
  import 'element-ui/lib/theme-default/index.css';
  export default {
    props: {
      params: {
        type: Object,
        default: {
          type: ''
        }
      },
      callback: {}
    },
    data() {
      return {
        x: 'hah',    
        numVal: ''
      };
    },
    methods: {
      handleChange(evt) {
        this.$emit('change', evt); // 将当前对象 evt 传递到父组件
      },
    },
    components: {
      'el-input': Input,
    }
  };
</script>

我自己的总结,不知道理解的是不是对,希望得到大家的批评建议。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值