父组件参数
<template>
<div>
<h2>子组件联动的与使用</h2>
<!-- reactive这样 -->
<!-- <childCom v-model:user="data.user" v-model="money" /> -->
<!-- ref这样 -->
<childCom v-model:user="user" v-model="money" />
</div>
</template>
<script setup>
import childCom from './components/childCom.vue';
import { reactive, ref } from 'vue';
/**
* todo 这样子组件重新赋值就不是响应式了
* const data = reactive({
name: '张三',
age: 28
})
*/
// 应该这样写
/* const data = reactive({
user: {
name: '张三',
age: 28
}
}) */
// 这个跟上面的响应式一样
const user = ref({
name: '张三',
age: 28
})
const money = ref(10000)
</script>
defineEmits:触发事件(函数,等价于 $emit)
defineProps:父组件传过来的值进行类型验证
<template>
<div>
<div ref="child">这是子组件的ref</div>
<div>父组件传过来的值</div>
<div>
<span>姓名: {{ props.user.name }}</span>
<span style="padding-left: 10px;">年龄: {{ props.user.age }}</span>
</div>
<div>还剩余存款:{{ props.modelValue }}</div>
<div>
<el-button @click="$emit('update:modelValue', props.modelValue - 1000)">向父亲要1000元生活费</el-button>
<el-button @click="handleInfo">过了一年父亲大了一岁</el-button>
</div>
</div>
</template>
<script setup>
// 接收父组件传过来的值
// 一个子组件只接收一个默认的v-model值
const props = defineProps({
// 接收v-model:user的值,不自定义名称的话默认就叫v-model
user: {
type: Object,
default: () => {}
},
// 接收v-model的值,不自定义名称的话默认就叫v-model
modelValue: {
type: Number,
default: 0
}
})
const $emit = defineEmits(['update:modelValue', 'update:user'])
const handleInfo = () => {
const info = {
name: props.user.name,
age: props.user.age + 1
}
$emit('update:user', info)
}
</script>