vue3 父传子 子传父; Vue3在父组件中触发子组件的方法

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值