vue3 父子组件传值和方法
1.子传父
1.1 利用defineExpose 传方法和值
<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:'默认标题'
},
})
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>