非响应式变量也随响应式变量一起变化,是设计如此还是bug呢?
Vue version
https://sfc.vuejs.org/vue.runtime.esm-browser.js
Link to minimal reproduction
Steps to reproduce
可查看演练场的例子,点击按钮
What is expected?
非响应式变量不应该响应
What is actually happening?
非响应式变量也响应了
System Info
No response
Any additional comments?
我看了编译后的代码,能理解,但为什么这样设计呢?而选项式的setup则不会这样,对应的例子是
在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__
@zhangzhonghe I guess it's designed for DevTools in dev mode. There's return __returned__
, and it lost reactivity.
But in production mode, there's no return __returned__
. The render function referenced the variables directly.
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