vue3 父子组件传值和方法

vue3 父子组件传值和方法

1.子传父

1.1 利用defineExpose 传方法和值

// 子组件 PlotProjectForm.vue 
<script setup>
import { ref, defineExpose } from 'vue';
import { Form } from 'ant-design-vue';

const visible = ref(false);

const showModal = () => {
  visible.value = true;
};

// 主动暴露方法/值
defineExpose({ visible, showModal})
</script>
// 父组件

<template>
  <PlotProjectForm ref="plotProjectFormRef" />
</template>

<script>
import { ref, onMounted } from 'vue'
import PlotProjectForm from '../components/Form/PlotProjectForm.vue'

export default {
  components: {
    PlotProjectForm,
  },
  setup() {
    
    const plotProjectFormRef = ref(null); // 子组件实例

    const showForm = () => {
      console.log(plotProjectFormRef.value.visible)
      plotProjectFormRef.value.showModal()
      console.log(plotProjectFormRef.value.visible)
    };
    
	return { plotProjectFormRef }
  }
}

1.2 利用emit传值

// 父组件
<template>
  <PlotProjectForm @cancelInfo="getCancelInfo" />
</template>

<script setup>
const isPlotInfo = ref(false)        // 确定是否绘制
const getCancelInfo = (value) => {
  isPlotInfo.value = value
  console.log(isPlotInfo.value)
}

console.log(isPlotInfo.value)
<script>
// 子组件
<script setup>
import { ref, defineEmits } from 'vue';

const visible = ref(false)

const emit = defineEmits(['cancelInfo'])

const handleCancel = () => {  // 处理点击取消按钮事件
  visible.value = false;
  emit('cancelInfo', visible.value)
};

<script>

2.父传子

1.1 利用defineProps传值

// 父组件
<template>
  <PlotProjectForm :fatherTitle="title" />
</template>

<script>
import { ref, onMounted } from 'vue'
import PlotProjectForm from '../components/Form/PlotProjectForm.vue'

export default {
  components: {
    PlotProjectForm,
  },
  setup() {
    const title = ref("-----这是父组件的标题-----")
    const printHello = () => {
    	console.log("hello")
    }
    return { title, printHello }
  }
}
<script>
// 子组件
<script setup>
import { ref, defineExpose } from 'vue';

const props = defineProps({
	fatherTitle:{
		type:String,  //类型字符串
		default:'默认标题' //如果没有传递msg参数,默认值是这个
	},
})

console.log(props.fatherTitle)
<script>

1.2 利用emit传方法

// 父组件
<template>
<PlotProjectForm @onMySonFunc="funcToSon" />
</template>

<script setup>
const funcToSon = (name, id)=>{
  console.log(name)
	console.log("子组件调用了父组件的funcToSon()方法",id)
};
</script>
// 子组件
<script setup>
import { ref, defineExpose } from 'vue';

const emit = defineEmits(['onMySonFunc'])

emit("onMySonFunc","调用父组件的方法",666666)
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

long11350

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值