vue3中props传值无法被watch监听的解决办法

2,945 阅读1分钟

代码如下 childen.vue

<script setup>
import {watch,ref} from "vue";

const props = defineProps({
  obj: {
    type: Object,
    default: () => ({
        name:'阿成'
    })
  }
})
const name = ref('')
watch(() => props.obj.name,(val)=>{
    console.log(val)
  	name.value = val
})
</script>

<template>
  <div  class="app-container">
    {{name}}-{{obj.name}}
  </div>
</template>


parent.vue

<script setup lang="ts">
  import {reactive} from "vue";
  import Comp from './Comp.vue'

const obj = reactive({
  name:'aCheng'
})
const click = () => {
  obj.name = 'Cheng'
}
</script>

<template>
  <div  class="app-container">
    <button @click="click">
      按钮
    </button>
      <Comp :obj='obj'></Comp>
  </div>
</template>

以上这种watch是监听不了的,需要改成以下这种 childen.vue

<script setup>
import {watch,ref,computed,toRefs} from "vue";

const props = defineProps({
  obj: {
    type: Object,
    default: () => ({})
  }
})
const name = ref('')
const objname = computed(() => props.obj.name)
watch(objname,(val)=>{
  name.value = val
})
</script>

<template>
  <div  class="app-container">
    {{objname}}-{{obj.name}}-{{name}}
  </div>
</template>