Vue3之emits


emits:Vue3中emits类比于Vue2的props,也是传值,但是Vue2props不能声明事件,Vue3emits可以声明事件

//Vue2
<template>
  <div>
    <p>{{ text }}</p>
    <button v-on:click="$emit('accepted')">OK</button>
  </div>
</template>
<script>
  export default {
    props: ['text']
  }
</script>

//Vue3
<template>
  <div>
    <p>{{ text }}</p>
    <button v-on:click="$emit('accepted')">OK</button>
  </div>
</template>
<script>
  export default {
    props: ['text'],
    emits: ['accepted']
  }
</script>

 

这里要注意,Vue3组件可以没有根元素,但是在组件的组件内触发事件时,如果为多个代码片段没有根元素包裹,会产生警告,需要对事件定义emits 

//警告代码
<template>
  <div class="checkout-address">
  </div>
  <x-dialog title="切换收货地址" v-model:visible="visible">
      <click-btn type="primary" @click="visible = false">确认</click-btn>
  </x-dialog>
</template>

setup(){
    emit("change", showAddress.value && showAddress.value.id); } //修改代码1 <template> <div class="checkout-address"> <x-dialog title="切换收货地址" v-model:visible="visible"> <click-btn type="primary" @click="visible = false">确认</click-btn> </x-dialog> </div> </template>  setup(){ emit("change", showAddress.value && showAddress.value.id); } //修改代码2 <template> <div class="checkout-address"> </div> <x-dialog title="切换收货地址" v-model:visible="visible"> <click-btn type="primary" @click="visible = false">确认</click-btn> </x-dialog> </template>  emits: ["change"], setup(){ emit("change", showAddress.value && showAddress.value.id); }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM