defineProps的基本使用:
父组件
<template>
<PropsAndEmit label02="小黄" />
</template>
<script setup>
import PropsAndEmit from "../components/PropsAndEmit.vue";
</script>
子组件
<template>
<div>{{label01}}</div>
<div>{{label02}}</div>
</template>
<script setup>
defineProps({
label01:{
type:String,
default:"小红"
},
label02:{
type:String,
default:"小红"
}
})
</script>
type是值的类型,default是默认值,运行的结果为:
defineEmits的基本使用:
父组件
<template>
<PropsAndEmit @btn="handleAdd" />
</template>
<script setup>
import PropsAndEmit from "../components/PropsAndEmit.vue";
const handleAdd = () => {
alert("点击了~")
}
</script>
子组件
<template>
<button @click="handleBth">按钮</button>
</template>
<script setup>
const emit = defineEmits(["btn"])
const handleBth = () => {
emit("btn")
}
</script>
得到的结果为:
defineEmits中的v-model的使用:
父组件
<template>
<PropsAndEmit @btn="handleAdd" v-model="num" />
</template>
<script setup>
import { ref } from "@vue/reactivity";
import PropsAndEmit from "../components/PropsAndEmit.vue";
let num = ref()
const handleAdd = () => {
num.value = num.value +1
}
</script>
子组件
<template>
<div>{{count}}</div>
<button @click="handleBth">按钮</button>
</template>
<script setup>
import { ref } from "@vue/reactivity"
defineProps({
modelValue:{
type:Number,
}
})
const emit = defineEmits(["update:modelValue","btn"])
let count = ref(0)
const handleBth = () => {
emit("update:modelValue",count)
emit("btn")
}
</script>
得到结果如下,点击按钮,count+1: