Vue2.0父子组件传递函数的教程详解

Vue.js (读音 /vjuː/,类似于 view) 是一套构建用户界面的渐进式框架。与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计。Vue 的核心库只关注视图层,它不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与单文件组件和 Vue 生态系统支持的库结合使用时,Vue 也完全能够为复杂的单页应用程序提供驱动。

学习笔记:在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>

总结

以上所述是小编给大家介绍的Vue2.0父子组件传递函数的教程详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wywsxw.html