Vue3語法糖-emit子對父傳值

父元件程式碼如下

  • 引入ref,申明宣告,接收子傳給父的數據
  • 接收子傳給父的數據放於template
  • 在template 子組件childClick=>子組件設定的觸發事件childClick
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<!--子對父傳值時-->
<child @childClick="childValFn"/>
<div>{{ childData }}</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// 引入子元件
import child from './child.vue'

const childData = ref(null)
const childValFn = (e: any) => {
//接收子组件傳遞给父组件的值
childData.value = e.value
}
</script>

子元件程式碼如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<div>
<!--子對父傳值時-->
<button class="el-button el-button--success" @click="toEmit">子组件向外傳遞數據</button>
</div>
</template>
<script setup>
//Vue3.2 版本后 defineProps 和 defineEmits 無需再導入
import {ref} from 'vue'

const childrenSay = ref('我是小孩')
const emits = defineEmits(['childClick'])
//點擊事件,向父組件傳值
const toEmit = () => {
// 觸發父組件事件childClick攜帶參數
emits('childClick', childrenSay)
}
</script>

語法糖子對父傳值