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>