vue3父子传值

1.父传子

父组件

<template>
  <div>
    <h1>父组件</h1>
    <son :value="parentValue"></son>
    <!--父组件给子组件传的值-->
  </div>
</template>
<script setup>
import { ref } from 'vue'
import son from '../components/SonView.vue'
components:{
  son
}
//定义传的值
const parentValue = ref('父传给子的值')
</script>

子组件

<template>
  <div>
    <h1>子组件</h1>
    <div>{{ value }}</div>
  </div>
</template>
<script setup>
import { ref, defineProps } from 'vue'
//用defineProps接收
const props = defineProps({
  value: {}
})
//可以动态修改传过来的值
const isValue = ref(props.value)
</script>
2.子传父

父组件

<template>
  <div class="father">
    <h1>父组件:{{ fatherMsg }}</h1>
    <!--自定义方法-->
    <son @getMsessage="getMsessages"/>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
import son from "../components/SonsView.vue";
export default defineComponent({
  components: {
    son
  },
  setup() {
    const fatherMsg = ref("");
    //自定义方法中的params参数接收
    function getMsessages(params) {
      fatherMsg.value = params;
    }
    return {
      fatherMsg,
      getMsessages
    };
  },
});
</script>
<style scoped>
.father {
  width: 200px;
  height: 200px;
  border: 1px solid red;
}
</style>

子组件

<template>
  <div class="son">
    <h2>子组件</h2>
    <button @click="getMsessage1">点我传值给父组件</button>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup(prop, ctx) {
    const message = ref("子组件的值--张三");
    function getMsessage1() {
      //通过自定义方法名传参
      ctx.emit("getMsessage", message);
    }
    return {
      message,
      getMsessage1,
    };
  },
});
</script>
<style scoped>
.son {
  width: 200px;
  height: 100px;
  border: 1px solid green;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值