1、父
<template>
<div>
<div>父</div>
<Son :txt="txt" @clickMe="clickMe"/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import Son from './son.vue';
export default defineComponent({
components: {
Son
},
setup() {
const txt = ref('我是父页传子的文字')
function clickMe (val) {
console.log('子传回来');
console.log('val-------: ', val);
};
return {
txt,
clickMe
};
},
});
</script>
<style scoped lang="less">
</style>
2、子
<template>
<div>
<div>子</div>
<p> {{txt}}</p>
<div @click="clickMe"> 点我 </div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, toRefs } from 'vue';
export default defineComponent({
props: {
txt: String
},
setup(props, {emit}) {
console.log('props ===>', props, props.txt)
const {txt} = toRefs(props)
console.log('txts ===>', txt)
let text = ref<number>(0);
function clickMe () {
let param = {
contents: '点击了我'
}
emit('clickMe', param)
};
return {
text,
clickMe
};
},
});
</script>
<style scoped lang="less">
</style>
0、Vue3在父组件中触发子组件的方法
在vue3中推出了
Vue3中的父组件中
父组件
<LoginAccount ref="accountRef"></LoginAccount>
<script lang="ts" setup>
import LoginAccount from './login-account.vue'
import { ref } from 'vue'
const accountRef = ref<InstanceType<typeof LoginAccount>>()
const handleLoginClick = () => {
console.log('ok', accountRef.value)
accountRef.value?.loginAction()
}
</script>
方法一:在子组件中使用defineComponent
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const loginAction = () => {
console.log('登录');
}
return {
loginAction,
}
}
})
</script>
方法二:使用defineExpose
<script lang="ts" setup>
import { reactive, ref, defineExpose } from 'vue'
const loginAction = () => {
console.log('登录');
}
defineExpose({
loginAction
})
</script>
参考:
https://blog.csdn.net/LiaoFengJi/article/details/120013255