一、页面效果图
二、父组件代码
<template>
<div class="user-box">
<div>
<h2>父组件:</h2>
<p>propRef:{{ propRef }}</p>
<p>propReactive:{{ propReactive }}</p>
</div>
<div>
<Child :propRef="propRef" :propReactive="propReactive" @emitValue="getEmitValue" ref="childRef" />
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, nextTick, toRefs, computed, provide } from 'vue';
import Child from './components/Child.vue';
const childRef = ref();
const propRef = ref('我是父组件通过Ref定义的值');
const propReactive = reactive({ name: '我是父组件的通过Reactive定义的值', path: 'index' });
const provideValueData = reactive({ name: 'provide', type: 'object' });
provide('provideValue', provideValueData);
function getEmitValue(value) {
console.log('子组件emit的值', value);
}
onMounted(() => {
console.log('打印子组件的ref对象', childRef.value);
});
</script>
<style type="text/css" lang="less">
.user-box {
padding: 20px;
}
</style>
三、子组件代码
<template>
<div>
<h2>子组件:</h2>
<div>
<h3>Props:</h3>
<p>propRef:{{ propRef }}</p>
<p>propReactive:{{ propReactive }}</p>
<p>propDefault:{{ propDefault }}</p>
</div>
<div>
<h3>Computed:</h3>
<p>computerMode1:{{ computerMode1 }}</p>
<p>computerMode2:{{ computerMode2 }}</p>
</div>
</div>
<div>
<h3>Emit:</h3>
<a-button type="primary" @click="emitToParent">Emit给父组件</a-button>
</div>
<div>
<h3>Watch:</h3>
<a-button type="primary" @click="addWatch">触发Watch</a-button>
</div>
<div>
<h3>inject</h3>
<div>data:{{ provideValue }}</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, watchEffect, defineEmits, defineProps, withDefaults, inject } from 'vue';
interface Props {
propRef: string;
propReactive: any;
propDefault?: string;
}
const props = withDefaults(defineProps<Props>(), {
propRef: '',
propReactive: { name: '', path: '' },
propDefault: '',
});
const provideValue = inject('provideValue');
const emits = defineEmits(['emitValue']);
const emitValue = ref('我是子组件的emit,我被发射了');
function emitToParent() {
emits('emitValue', emitValue.value);
}
const watchValue = ref(1);
function addWatch() {
watchValue.value++;
}
watch(
watchValue,
(oldValue, newValue) => {
console.log('[ oldValue,newValue ]', oldValue, newValue);
},
{ immediate: true, deep: true }
);
watchEffect(() => {
console.log('通过watchEffect监听watchValue的值的变化:', watchValue.value);
});
const computedValue1 = ref(1);
const computedValue2 = ref(10);
const computerMode1 = computed(() => {
return computedValue1.value + computedValue2.value;
});
const computerMode2 = computed({
get() {
return computedValue1.value + computedValue2.value;
},
set() {
return computedValue1.value + computedValue2.value;
},
});
const childValue = ref('我是子组件的值');
function childFunction() {
console.log('我是子组件的方法');
}
defineExpose({
childValue,
childFunction,
});
</script>