vue3--父子组件传值

vue3中新的用法<script setup></script>setup放在<script></script>

emit 子组件向父组件传值

子组件 child.vue

<script setup>
const state = reactive({
 active: '1234'
})
const emit = defineEmits(['confirm']) 
const confirm = () => {
 emit('confirm', state.active)
}
<script>

父组件 parent.vue

<child @confirm="confirm"/>
import child from './child.vue'
const confirm = (value) => {
 console.log(value, '子组件传过来的值')
 console.log('这里是父组件')
}

props 父组件向子组件传值

父组件 parent.vue

<child :parentValue="parentValue" :parentFunction="parentFunction"/>
import child from './child.vue'
import { reactive, toRefs } from 'vue' // 引入 
const state = reactive({
 parentValue: '我是parent中的值'
})
const { parentValue } = toRefs(state)
const parentFunction = () => {
 console.log('我是parent中的方法')
}

子组件 child.vue

<template>
 {{parentValue}}
</template>
<script setup>
const props = defineProps({
    parentFunction: Function,
    parentValue: {
      type: String,
      default: ''
    }
  })
 console.log(props.parentValue, props.parentFunction) // 在 script 中使用的时候 需要带上 props
</script>

使用子组件中的变量合方法 — ref 和defineExpose

子组件 child.vue

<script setup>
import { reactive, toRefs } from 'vue'
const childFunction = () => {
  console.log('子组件中的方法')
}
const state = reactive({
 childState: 'child'
})
defineExpose({ // 一定要使用 defineExpose 将你要在父组件中使用的方法 导出
childFunction,
state.childState
})
</script>

父组件 parent.vue

<child ref="child"/>
import child from './child.vue'
import { reactive, toRefs, ref } from 'vue' // 引入 
const child = ref(null)
console.log(child.value.childFunction, child.value.childState)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值