vue2.6 自定义组件踩坑

关于自定义组件 自定义事件上代码

 通过代码发现,一个是默认的自定义事件,一个是自定义的时间,它们是在调用,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>

小结: 

自定义事件这么写是比较好的,子组件定义好方法后,通过点击事件传递给父组件,父组件能接受到数据,也能接受到自己定义的方法,相当于子组件操作父组件的数据,那么

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaodunmeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值