传递给vue3构建的web组件的Vue2属性

yc0p9oo0  于 2023-03-24  发布在  Vue.js
关注(0)|答案(1)|浏览(123)

我有个很具体的问题
所以我使用vue2作为我的主项目,同时我也使用我的vue3 web组件项目作为vue2项目中的npm库(我基本上是公开vue3构建的web组件)。
问题是,当我从vue2项目中传递一个对象到vue3 web组件,然后更改一些对象属性时(例如,我有数组作为对象属性,我把新的值推到它)它不触发任何监视器或计算(即监视该属性)在我的vue3 web组件中,它根本看不到更改,看到更改的唯一方法是复制对象,但这并不理想。我尝试使用Vue3到Vue3 Web组件,然后它就像一个魅力。
有人能帮我解释一下吗?
Vue2项目,当我添加deep watcher时会看到变化:

<template>
  <div>
    <problem
        :testObject.prop="testObject"
        @testEmit="pushArray"
    />
    {{ testObject }}
  </div>
</template>

<script>
export default {
    data()
    {
        return {
            testObject: null,
        };
    },
    created()
    {
        this.testObject = {
            objectArray: [1, 2],
        };
    },
    methods:
    {
        pushArray()
        {
            this.testObject.objectArray.push(5);
        },
    },
    watch: {
       testObject:
       {
           handler(newVal)
           {
               console.log('View watcher triggered', newVal);
           },
           deep: true,
       },
   },
};
</script>

Vue3 web组件(导出时定义为web组件)未通过深度观察器看到变化,也未计算在属性发生变化时应触发的内容:

<template>
    <div>
        Prop Object {{ testObject }}
        <hr>
        Ref Object {{ objectWithArray }}
        <br>
        <button @click="pushArray">
            Push array
        </button>
    </div>
</template>

<script lang="ts">
import {defineComponent, watch, computed} from 'vue'

export default defineComponent(
{
    props: {
        testObject: {
            type: Object,
            default: () => (null),
        }
    },
    emits: ['testEmit'],
    setup(props, ctx)
    {
        const objectWithArray: any = computed(() => 
        {
            console.log('Computed triggered');
            return props.testObject;
        })

        const pushArray = () =>
        {
            ctx.emit('testEmit');
        }
        

        watch(
            () => props.testObject,
            (newVal) => 
            {
                console.log('Component watcher triggered', newVal);
            },
            {deep: true}
        )

        return {
            pushArray,
            objectWithArray
        }
    }
})
</script>
ggazkfy8

ggazkfy81#

这是Vue 2中props的正常行为

默认情况下,他们不会“观看”到更深的层次。
文档中的Vue 2中的两个解决方案:https://vuejs.org/guide/essentials/watchers.html#deep-watchers

1.显式监视特定属性

watch: {
    'some.nested.key'(newValue) {
      // ...
    }
}

2.深度观看整个 prop

export default {
  watch: {
    someObject: {
      handler(newValue, oldValue) {
        // Note: `newValue` will be equal to `oldValue` here
        // on nested mutations as long as the object itself
        // hasn't been replaced.
      },
      deep: true
    }
  }
}

下面是@yoduh关于Vue 3 composition API在默认情况下进行深度观察的精彩观点。

相关问题