父传子
<template>
<h2>父</h2>
<child :str="str"></child>
</template>
<script setup>
import {ref} from "vue"
import child from "./child.vue"
let str = ref("父组件传入的数据")
</script>
<template>
<h2>子</h2>
{{ str }}
</template>
<script setup>
defineProps({
str: { type: String, default: "strzzz" },
})
</script>
子传父
<template>
<h1>父组件: {{ fatherMsg }}</h1>
<son @clickFather="clickFather" />
</template>
<script setup>
import { ref } from "vue";
import son from "./son.vue";
const fatherMsg = ref("");
function clickFather(params) {
fatherMsg.value = params; // 我传的这个params是个普通的字符串
}
</script>
<template>
<h2>子组件</h2>
<button @click="clickSon">点我</button>
</template>
<script setup>
import { defineProps, defineEmits, ref } from "vue";
const emits = defineEmits(["clickFather"]); // 这个名字和下面emits的名字保持一致
function clickSon() {
emits("clickFather", "我是子组件传给父组件的值");
}
</script>
兄弟互传
先 npm i mitt
,然后创建文件夹和文件 plugins/Bus.js
,
A、B组件import emitter from "../plugins/Bus.js"
依赖注入(provide和inject)
注意可以修改值,两者会一起改