Subscribe on changes!

Will trigger template update although deps data actually has not changed.

avatar
Apr 28th 2023

Vue version

Both 3.2.47 and 3.3.0-beta.2

Link to minimal reproduction

https://play.vuejs.org/#eNp9Ud1K80AQfZX5lg+SQptYFYTQloo3PoDgzV4Yk2kb3T92J1UJeXdnk1prBa+WPXNmzjkznbh1Ltu3KAqxCJVvHEFAat1KmkY76wk68LiZQmW1awlr6GHjrYaEmxJppKmsCQQ6bGEZmWlyj0pZeLRe1f+SyReBrDsQLo5YoA+FjH7NTtMJLFeQdpFdwNP/jt9sX6oWe/f+BP2EW6XZtKaixhogDMQtnTQQO0Ymz5tfnCMM9BE7afZoavQpGz9MiJ6swkzZbZqU0TkwiVpvYrphwCIfd8Tb4Q+hdqok5B/AYjeHYgi0lGJ4pYB1pZrqlYHoVIpVF5f5Ldv3i3w3H9rvIhHKZ7tHeGiI14J79B/UaJwCuwF2teXtN+boM9o5WhBTMd5rpkuXvQRr+KJDLHkoBCmKMWjE+HrxL8WOyIUiz1vjXrcZXyJfcy33rYnas9rq9VV2mV3f5HUT6BTPMOjZs7dvAT0rSjE9GZ4zyAFmY1z0f4qdcX8IntV+iUZNvkwv+k/U7Pa3

Steps to reproduce

You just only need to click the title (h1), and view the console in brower devtools panel.

What is expected?

Only one log for initialization, and no log when click.

What is actually happening?

A new log when click everytime.

If you comment out the line 9 top.value = 10, the behavior is same to expected.

System Info

No response

Any additional comments?

No response

avatar
Apr 28th 2023

Maybe this behavior is expected, see https://vuejs.org/guide/essentials/computed.html#computed-caching-vs-methods.

If so, you can close this issue.

avatar
Apr 28th 2023

Now I using customRef to imrpove this:

import { customRef } from 'vue'

const triggerSet = new Set<() => void>()

function manualRef<T>(value: T) {
  return customRef<T>((track, trigger) => {
    let origin = value

    const update = () => {
      if (value !== origin) {
        origin = value
        trigger()
      }
    }

    return {
      get: () => (track(), value),
      set: newValue => {
        if (newValue === value) return

        value = newValue
        triggerSet.add(update)
      }
    }
  })
}

function triggerUpdate() {
  for (const trigger of triggerSet) {
    trigger()
  }

  triggerSet.clear()
}

Usage:

const top = manualRef(0)

top.value = 10
top.value = 0

triggerUpdate() // no trigger called
avatar
Apr 28th 2023

This is expected, yes.