Vue3-父子组件小案例

99 阅读1分钟

父组件传递信息到子组件:

  • 父组件中给子组件绑定属性
  • 子组件内部通过props选项接收数据

子组件传递信息到父组价

  • 父组件中给子组件标签通过@绑定事件
  • 子组件内部通过 emit 方法触发事件

父亲负责给钱,儿子负责花钱

image.png

父亲:

<script setup>
import sonCom from '@/components/son.vue'
import { ref } from 'vue'
const money = ref(100)
const addMoney = () => {
  money.value += 10
}
const subMoney = () => {
  money.value-=20
}
</script>

<template>
  我是父亲
  <sonCom :money="money" @subMoney="subMoney"></sonCom>
  <button @click="addMoney">加钱</button>
</template>

这是儿子

<script setup>
defineProps({
  money:Number
})

const father=defineEmits(['subMoney'])
const buy=()=>{
  father('subMoney')
}
</script>

<template>
  <div class="son">
    我是儿子我有{{money}}元
    <button @click="buy">花钱</button>
  </div>
</template>

<style scoped>
.son {
  border: 1px solid #000;
  padding: 80px;
}
</style>