vue3的新写法和特性整理——四、子父组件之间传值
只贴出了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) 的结构即可
效果图
随笔为本人学习笔记以及个人看法,若有错误,欢迎指正

浙公网安备 33010602011771号