父组件HelloWorld
子组件defineComponent和setup(使用
父组件HelloWorld
<template>
<h1>Count: {{ count }}</h1>
<input v-model="count" type="number">
<DefineComponent :count="count" @add-count="addCount" @sub-count="subCount"></DefineComponent>
<Setup :count="count" @add-count="addCount" @sub-count="subCount"></Setup>
</template>
<script lang="ts">
import DefineComponent from "./defineComponent.vue";
import Setup from "./setup.vue";
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "HelloWorld",
components: {
DefineComponent,
Setup
},
setup() {
const username = ref("Gee");
const addCount = () => {
count.value++
}
const subCount = () => {
count.value--
}
const count = ref(0)
return {
count,
username,
addCount,
subCount
};
},
});
</script>```
子组件defineComponent
<template>
<div style="border: 1px solid pink">
<h1>defineComponent</h1>
<div class="main" ref="htmlRef">
<h3>{{ username }} is {{ age }}.</h3>
<h3>count相乘:{{ showCount }}</h3>
<button @click="subCount">-</button>
<button @click="addCount">+</button>
<Unit></Unit>
<Unit></Unit>
<Unit></Unit>
<Unit></Unit>
</div>
</div>
</template>
<script>
import { computed, defineComponent, ref, toRefs, watch } from "vue";
// components
import Unit from "./unit.vue"
export default defineComponent({
name: "",
components: {
Unit
},
props: {
count: {
type: Number,
required: true
},
},
emits: ['add-count', 'sub-count'],
setup(props, context) {
// data
const username = ref("Cindy")
const age = ref(23)
// props
const { count } = toRefs(props) // ref对象
// computed
const showCount = computed(() => count.value * count.value)
// watch props
watch(count, (newVal) => {
console.log('传入的count改变:', count);
})
// methods
const addCount = () => {
context.emit('add-count')
}
const subCount = () => {
context.emit('sub-count')
}
return {
username,
age,
showCount,
addCount,
subCount
}
},
});
</script>
子组件setup(使用<script setup>法糖)
<template>
<div style="border: 1px solid">
<h1>Setup</h1>
<h3>{{ username }} is {{ age }}.</h3>
<h3>count相乘:{{ showCount }}</h3>
<h3>直接显示props数据:{{ props.count }}</h3>
<button @click="subCount">-</button>
<button @click="addCount">+</button>
<button @click="emit('sub-count')">直接绑定emit</button>
<Unit></Unit>
<Unit></Unit>
<Unit></Unit>
<Unit></Unit>
</div>
</template>
<script setup>
// components 引用后就可以直接使用components
import Unit from "./unit.vue"
import { defineProps, ref, computed, toRefs, watch, defineEmits } from "vue"
// props
const props = defineProps({
count: {
type: Number,
required: true
}
})
const { count } = toRefs(props);
console.log('props', props.count);
// data
const username = ref("Cindy")
const age = ref(23)
// computed
const showCount = computed(() => count.value * count.value)
// watch props
watch(() => props.count, (newVal) => {
console.log('传入的count改变:', count);
}, { deep: true })
// methods
// emit
const emit = defineEmits(['add-count', 'sub-count'])
const addCount = () => {
emit('add-count')
}
const subCount = () => {
emit('sub-count')
}
</script>