1.父传子
index.vue
<template>
我是父组件
<Child :str="str" />
</template>
<script setup>
import Child from "./Child.vue";
import { ref } from "vue";
const str= ref("m"); // 传给子组件的值
</script>
Child.vue
<template>
我是子组件
<div>从父组件传进来的值:{{ str}}</div>
</template>
<script setup>
// 使用 defineProps 声明 props
const props = defineProps({
str: {
type: String,
default: "",
},
});
</script>
2.子传父
index.vue
<template>
我是父组件
<child @childChange="childChange" />
<p>{{ str}}</p>
</template>
<script setup>
import Child from "./Child.vue";
import { ref } from "vue";
const str= ref(""); // 从子组件传出的值
// 组件的自定义事件
const childChange = (val) => {
str.value = val;
};
</script>
Child.vue
<template>
我是子组件
<el-button @click="handleClick">点我触发自定义事件</el-button>
</template>
<script setup>
// 使用 defineEmits 声明 emits
const emit = defineEmits(["childChange"]);
const handleClick = () => {
// 必须经过defineEmits声明,不然方法无效!
emit("childChange", "我是经自定义方法传出的值");
};
});
</script>