Vue3中使用setup监听props

开发者 2024-9-22 07:12:31 35 0 来自 中国
配景形貌

子组件展示父组件传来的参数,展示的信息随着父组件上tab的切换动态更新。
一开始的想法是单独监听这个通报的参数,但看了VUE3的文档之后,似乎对参数的监听必须准确到属性。比方参数为
{      name: 'Doctor',      gender: 'Timelord'}必要在子组件的watch中写明监听的是name照旧gender。
该参数中有许多大概会改变的属性,逐一监听过于贫困。以是改变思绪,使用监听props来获取全部全部传参。
实现方法

在父组件中,用于通报给子组件的参数必须为相应式(eg. reactive),否则子组件在监听时不会监测到变更,watch永久不访问效
immediate是立刻开始监听,在页面初次渲染时大概为体现为undefined,如果watch的变革必要手动触发,不必要开启
deep默认开启,可以忽略(参数为reactive,会默认开启deep,如果是ref,则不会默认开启deep)
// 父组件<script>export default {  setup() {    let traveller = reactive({      name: 'Doctor',      gender: 'Timelord'    })  }}</script>// 子组件<script>export default {  props: {    traveller: {      type: Object    }  }  setup(props) {    watch(            props,            (old, newProps) => {                console.log('=======', newProps); //这里看到新值            },            // {               //     immediate: true,            //     deep: true            // }        )  }}</script>
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:51, Processed in 0.143523 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表