Subscribe on changes!

非响应式变量也随响应式变量一起变化,是设计如此还是bug呢?

avatar
Oct 11th 2022

切换编译环境会有不同的结果 image

avatar
Oct 11th 2022

在render函数中,直接取值,而未通过$setup.xx或者_ctx.xx取值,在render函数重新执行来更新界面时,未响应的值会搭响应值的顺风车,渲染出最新的值到界面。正如https://github.com/vuejs/core/issues/6850#issuecomment-1273994466 所说,不同的编译环境也会选择是否通过$setup.xx取值或者_ctx.xx取值或者直接取值。

就像下面这样:

/* Analyzed bindings: {
  "ref": "setup-const",
  "count1": "setup-ref",
  "count2": "setup-let",
  "onClick": "setup-const"
} */
import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, unref as _unref, createTextVNode as _createTextVNode, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

import { ref } from 'vue'


const __sfc__ = {
  __name: 'App',
  setup(__props) {

const count1 = ref(1)
let count2 = 1

const onClick = () => {
   count1.value++
   count2++
}

return (_ctx, _cache) => {
  return (_openBlock(), _createElementBlock("div", null, [
    _createElementVNode("button", { onClick: onClick }, " 点击 "),
    _createTextVNode(" " + _toDisplayString(count1.value) + "-- " + _toDisplayString(_unref(count2)), 1 /* TEXT */)
  ]))
}
}

}
__sfc__.__file = "App.vue"
export default __sfc__

Playground demo

avatar
Oct 11th 2022

我也有疑惑,生产环境和开发环境的编译结果不一致是出于什么考虑的呢?

avatar
Oct 11th 2022

@zhangzhonghe I guess it's designed for DevTools in dev mode. There's return __returned__, and it lost reactivity. image

But in production mode, there's no return __returned__. The render function referenced the variables directly.

avatar
Oct 11th 2022

This is working as expected. When returning the number, it’s being copied. Refs are not. Use a ref if you need it to be reactive

avatar
Oct 11th 2022

@posva so, why dev mode is different with build mode?