vue3.2 script setup 父子組件傳值


父組件代碼

<!-- 父組件代碼 -->
<template>
  <div id="nav">
    <AboutVue :value="parentValue" @add="onParentClick" />
    <br />
    <button @click.stop="onParentClick()">父組件按鈕</button>
  </div>
</template>
<script setup>
/**
 * 引入必要的模塊
 */
import { ref } from 'vue'
import AboutVue from './views/About.vue'
/**
 * 定義數據
 */
const parentValue = ref(0)

/**
 * 定義方法
 */
function onParentClick (childValue) {
  childValue ? (parentValue.value += childValue) : parentValue.value++
}
</script>
<style scoped>
#nav {
  text-align: center;
}
</style>

子組件代碼

<!-- 子組件代碼 -->
<template>
  <div class="about">
    <h1>{{ props.value }}</h1>
    <button @click="onChildClick">子組件按鈕</button>
  </div>
</template>
<script setup>
/**
 * 引入必要的模塊
 */
import { defineProps, defineEmits } from 'vue'
/**
 * 定義數據
 */
const props = defineProps({ value: { type: Number } })
const emit = defineEmits(['add'])

/**
 * 定義方法
 */
function onChildClick () {
  emit('add', 2)
}
</script>

 

vue3.2 setup 語法糖中:子組件使用 defineProps接收props , 使用 defineEmits傳遞給參數給父組件

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM