Reactive variable reassignment rendering failed
Vue version
^3.8.3
Link to minimal reproduction
https://github.com/huifer/vue3-reactive.git
Steps to reproduce
Write the following code
<template>
<div>
<p>{{ a.old_data }}</p>
<button @click="click">渲染</button>
<p>{{ a.new_data }}</p>
</div>
</template>
<script setup>
import {reactive} from "vue";
var a = reactive({
old_data: 1,
})
// eslint-disable-next-line no-unused-vars
function click() {
a = reactive({
new_data: 2,
old_data: 2
});
console.log(a);
}
// eslint-disable-next-line no-unused-vars
function click2() {
a.new_data = 2;
a.old_data = 2;
console.log(a);
}
</script>
<script>
export default {
name: 'App',
}
</script>
<style>
</style>
What is expected?
After the click method is executed, {{a. old_data}} and {{a. new_data}} on the page are rendered as 2
What is actually happening?
The page has not changed
System Info
System:
OS: macOS 12.3.1
CPU: (12) x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
Memory: 264.08 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 16.14.0 - /usr/local/bin/node
Yarn: 1.22.17 - /usr/local/bin/yarn
npm: 8.15.0 - /usr/local/bin/npm
Watchman: 2022.07.04.00 - /usr/local/bin/watchman
Browsers:
Brave Browser: 104.1.42.97
Chrome: 105.0.5195.125
Firefox: 103.0.2
Safari: 15.4
npmPackages:
vue: ^3.2.13 => 3.2.39
Any additional comments?
Do not use the following methods
function click2() {
a.new_data = 2;
a.old_data = 2;
console.log(a);
}
reassigning *variables *is never reactive, this is a limitation in Javascript. And the reason why ref()
exists.
If this is caused by variables, why use a new_ Data can be modified directly and rendered normally? I try to use the following code to try, but I can't render normally
<template>
<div>
<p>{{ a.old_data }}</p>
<button @click="click">渲染</button>
<p>{{ a.new_data }}</p>
</div>
</template>
<script setup>
import {ref} from "vue";
var a = ref({
old_data: 1,
})
// eslint-disable-next-line no-unused-vars
function click() {
a = ref({
new_data: 2,
old_data: 2
});
console.log(a);
}
</script>
<script>
export default {
name: 'App',
}
</script>
<style>
</style>
If this is caused by variables, why use a new_ Data can be modified directly and rendered normally?
I'm not sure what you mean here.
When I execute the click2 method, I render normally. I don't want to render in this way. I want to render directly by reassigning a