vue3 父子组件传值

一,子传父

父组件

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { ref } from 'vue'//直接赋值页面不会自动渲染,使用ref存储响应式数据
import { defineExpose } from "vue";父传子
let val = ref('');
const childFun= value =>{
  console.log('----',value)
  // 这里直接赋值value,在页面上直接使用val即可!
  val.value=value
  console.log('val',val)
}
</script>

<template>
  <header>
    <div class="wrapper">
      <HelloWorld @child="childFun"/>
    </div>
  </header>
<div>我是子组件过来的值:{{val}}</div>
</template>

子组件

<script setup>
import {  defineEmits } from 'vue'//子传父值先引用emits方法
 defineProps({
   msg: {
     type: String,
     required: true
  }
 })
//要先声明,不然会报错
const emits = defineEmits(['child'])
function tofu (){
  emits('child','123')
}
</script>

<template>
  <div class="greetings">
    <h1 class="green">msg</h1>
    <button @click="tofu">子组件按钮</button>
  </div>
</template>

二,父传子

父组件

<script setup>
import HelloWorld from './components/HelloWorld.vue'

</script>

<template>
  <header>
    <div class="wrapper">
      <HelloWorld msg='我是父组件'/>
    </div>
  </header>

</template>


子组件

<script setup>
 defineProps({
   msg: {
     type: String,
     required: true
  }
 })

</script>

<template>
  <div class="greetings">
    <h1 class="green">{{msg}}</h1>
  </div>
</template>

vue3和vue2区别还是有一些的,V2传值直接赋值,有时是可以直接数据响应渲染

setup可以直接写在script标签上,也可以写成函数形式

const声明的变量,在后期不能进行修改,不然会报错,需后期修改的变量尽量使用let ,var,根据情况使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值