Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch() doesn't trigger when adding new property with Vue.set( ) #12967

Closed
depressedX opened this issue Feb 21, 2023 · 2 comments
Closed

watch() doesn't trigger when adding new property with Vue.set( ) #12967

depressedX opened this issue Feb 21, 2023 · 2 comments

Comments

@depressedX
Copy link

depressedX commented Feb 21, 2023

Version

2.7.14

Reproduction link

codepen.io/AxisZ/pen/RwYrmxq

Steps to reproduce

Just open the codepen link, and open browser's devtool console

What is expected?

The Vue.set(obj, 'added', 1); statement should trigger the watcher callback, which will print [watch getter]obj changed.

What is actually happening?

nothing happened, the watcher does not be triggered


This behavior is not the same as neither vue2.6 or vue3.
Open this codepen writting with vue2.6+@vue/composition-api, It will print [watch getter]obj changed, which is expected.

vue2.6+@vue/composition-api demo: https://codepen.io/AxisZ/pen/VwGeOEE

The core codes is here:

const { watch, reactive, set } = Vue;

const obj = reactive({ exist: 1 });

watch(
    () => obj,
    () => {
        console.log('[watch getter]obj changed');
    },
    { deep: true },
);

setTimeout(() => {
    console.log('should print watcher message↓↓↓↓');
  // add a new property, should trigger that watch below as expected
    set(obj, 'added', 1);
});
@depressedX
Copy link
Author

depressedX commented Feb 21, 2023

found @vue/compositon-api tricky code here. Maybe there should also be something like this?

https://github.com/vuejs/composition-api/blob/1a05a1d4f2cdfdc1b66b094045b335d5605b2946/src/apis/watch.ts#L381-L391

  // if the return value is reactive and deep:true
  // watch for changes, this might happen when new key is added
  if (isReactive(watcher.value) && watcher.value.__ob__?.dep && deep) {
    watcher.value.__ob__.dep.addSub({
      update() {
        // this will force the source to be revaluated and the callback
        // executed if needed
        watcher.run()
      },
    })
  }

@shrpne
Copy link

shrpne commented Feb 28, 2023

maybe related to vuejs/composition-api#933

xiaowei-one pushed a commit to xiaowei-one/vue that referenced this issue Feb 28, 2023
xiaowei-one pushed a commit to xiaowei-one/vue that referenced this issue Feb 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants