关于自定义组件 自定义事件上代码
通过代码发现,一个是默认的自定义事件,一个是自定义的时间,它们是在调用,this.$emit(参数1,参数2) 的情况下调用的 参数1 指定父组件接收的方法,参数2位父组件接收的数据
<template> <div> <a-modal v-bind="$attrs" v-on="$listeners" v-bind:visible="value" v-on:change="value => $emit('input', value)" v-on:print="val => $emit('print',val)" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel" > <!-- 一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件 --> <p>{{ ModalText }}</p> <a-button @click="handleClose">close</a-button> </a-modal> </div> </template> <script> export default { name: 'ChangePayNew', props: { value: { type: Boolean, default: false } }, data () { return { confirmLoading: false, ModalText: '' } }, methods: { handleOk() { this.ModalText = 'The modal will be closed after two seconds'; this.confirmLoading = true; setTimeout(() => { this.$emit('input', false); // 关闭对话框 this.confirmLoading = false; // 关闭加载框 }, 2000); }, handleCancel() { console.log('handleCancel'); this.$emit('canclenew','xiaodunmengnew') // 通知父组件的cancle 方法带着参数 }, handleClose() { console.log('handleClose'); this.$emit('input', false); this.$emit('print', 'print'); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
父组件调用
通过代码发现有 showChangenew 上面有交代,
canclenew 是子组件指定交给父组件处理,父组件能接受参数val,还能接受,它自己的方法init
<template> <div> <a-button @click='showChangenew = true'>clicknew</a-button> <change-pay-new title="woshisui" v-model="showChangenew" @canclenew='val => homeCancelnew(val,init)' @print='val => getPrint(val)'></change-pay-new> </div> </template> <script> import ChangePayNew from './laravel/change-pay-new.vue' export default { name: 'HomeView', components: { ChangePayNew }, data() { return { dataList: [], showChangenew: false } }, methods: { getPrint(val) { console.log(val,'ppppp'); }, homeCancelnew(val,init) { console.log(val); console.log(init); this.showChangenew = false }, initnew() { this.dataList = [4,5,6] console.log('init',this.dataList); } }, created() { } } </script>
小结:
自定义事件这么写是比较好的,子组件定义好方法后,通过点击事件传递给父组件,父组件能接受到数据,也能接受到自己定义的方法,相当于子组件操作父组件的数据,那么