只貼出了vue3中新的子父組件傳值,V3兼容老的寫法就不再贅述
1、父組件
<template>
<div class="home">
<h1>父組件</h1>
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld :msg="msg" />
</div>
</template>
<script>
import { reactive, toRefs } from 'vue';
import HelloWorld from "@/components/HelloWorld";
export default {
setup() {
const state = reactive({
msg: '父組件傳值'
});
return {
...toRefs(state)
};
},
name: 'Home',
components: {HelloWorld},
};
</script>
<style scoped>
.home {
color: red;
border: 1px solid red;
}
</style>
2、子組件
<template>
<div class="hello">
<h1>子組件</h1>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
import { toRefs } from 'vue';
export default {
setup(props) {
console.log(props);
return {
...toRefs(props)
};
},
name: 'HelloWorld',
props: {
msg: String
}
};
</script>
<style scoped>
.hello {
margin: 20px;
color: green;
border: 1px solid green;
}
</style>
setup函數的第一個參數能取到父組件的傳值,然后在函數中返回 toRefs(props) 的結構即可
效果圖
