父组件
<template>
<div class="parent">
<Child :data="count" @handle="change" />
<button @click="add">父组件的按钮</button>
</div>
</template>
<script>
import Child from './components/child.vue'
import { defineComponent, reactive, toRefs } from 'vue'
export default defineComponent({
name: '',
props: {},
components: { Child },
setup () {
const state = reactive({
count: 1
})
const add = (): void => {
state.count += 1
}
const change= (num: number) => {
state.count += num
}
return {
...toRefs(state),
add,
changeValue
}
}
})
</script>
子组件
<template>
<div>
<div>{{data}}</div>
<button @click='changeParentNum'>子组件按钮</button>
</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'child',
props: {
data: Number
},
setup (props, ctx) {
const changeParentNum = () => {
// 通过ctx调用emit事件 需要注意的是Vue2.x中使用 $emit切勿混淆
ctx.emit('handle', 2)
}
return {
changeParentNum
}
}
})
</script>
子组件语法糖
<template>
<div>
<div>{{data}}</div>
<button @click='btn'>子组件按钮</button>
</div>
</template>
<script setup>
import { defineProps,defineEmits } from 'vue'
const props = defineProps({
data: {
type: Number
}
})
const emit = defineEmits(['handleOk']) // 这里可以写多个方法名
function btn(){
emit('handleOk',2)
}
</script>