与vue2的方法一样
父给子传值 props
我们通过在父组件引用子组件的时候,可以通过自定义属性进行值的传递,在子组件通过 props 进行接受。
父
<template>
<div class="main">
<div v-if="isScan"></div>
<rcode :tovalue="test"></rcode>
</div>
<!-- 与vue2的方法一样 -->
</template>
<script lang='ts'>
import rcode from "../components/login/QRcode.vue";
import { ref, watch, reactive, toRefs } from "vue";
export default {
name: "loginIndex",
components: { rcode },
setup() {
const test = ref("yangyang");
const data = reactive({
isScan: false,
list: "12121",
});
const refData = toRefs(data);
return {
...refData,
test,
};
},
};
</script>
<style lang="scss" scoped>
.main {
font-size: 16px;
}
</style>
子
<template>
<div class="qrCode">
{{ tovalue }}
</div>
</template>
<script lang='ts'>
import { reactive, toRefs } from "vue";
export default {
name: "",
props: ["tovalue"],
setup() {
const data= reactive({});
const refData = toRefs(data);
return {
...refData,
};
},
};
</script>
<style scoped>
</style>
子组件向父组件传递 emit
兄弟组件之间通讯
安装:npm i mitt -s
点击按钮,改变兄弟组件的值
1.父组件
<template>
<div>
<brotherC></brotherC>
<brotherD></brotherD>
</div>
</template>
<script>
import brotherC from "@/components/brother/brotherC";
import brotherD from "@/components/brother/brotherD";
export default {
name: "brotherLink",
components: {
brotherC,
brotherD,
},
}
</script>
2.子组件1
<template>
<div>
<h2>brotherC</h2>
<a-button @click="changeMsg" type="primary">点击修改msg</a-button>
</div>
</template>
<script>
import { reactive, ref } from "vue";
import emitter from "@/common/js/utils/mitt.js";
export default {
name: "brotherC",
setup() {
let changeMsg = () => {
emitter.emit('change-msg')
};
return {
changeMsg,
};
},
};
</script>
<style lang='scss' scoped>
</style>
3.子组件2
<template>
<div>
<h2>brotherD</h2>
<p>{{ msg }}</p>
</div>
</template>
<script>
import { reactive, ref, onUnmounted } from "vue";
import emitter from "@/common/js/utils/mitt.js"
export default {
name: "brotherD",
setup() {
let msg = ref("hello");
let changeMsg = ()=>{
msg.value = '我被改变啦';
}
emitter.on('change-msg',changeMsg)
onUnmounted(()=>{
console.log('onUnmounted')
emitter.off('change-msg',changeMsg)
})
return {
msg,
changeMsg
};
},
};
</script>
<style lang='scss' scoped>
</style>
4.mitt.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;
|