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);
}

 

posted @ 2021-12-25 10:33  Jacky02  阅读(4773)  评论(0)    收藏  举报