Check out this code snippet:
<template>
<input type="button" value="click" @click="clickBtn"/>
<div id="reactiveDiv">{{ reactiveVariable }}</div>
<div id="noneReactiveDiv">{{ noneReactiveVariable }}</div>
</template>
<script setup lang="ts">
import { ref, nextTick } from "vue"
const reactiveVariable = ref('reactive')
let noneReactiveVariable = 'non reactive '
function clickBtn(){
reactiveVariable.value = (new Date().getTime()).toString()
noneReactiveVariable = (new Date().getTime()).toString()
nextTick(()=>{
console.log('next tick')
})
}
</script>
In the provided code, there are two variables: reactiveVariable which is reactive and noneReactiveVariable which is not.
The main question arising here is:
Upon clicking the button, both variables in the template change. It appears that even though noneReactiveVariable is not defined with a ref or reactive keyword, it still changes when reactiveVariable's value changes. This behavior may be due to the update triggered by the change in reactiveVariable. Further investigation is required to confirm this assumption.
If we modify the template as follows:
<template>
<input type="button" value="click" @click="clickBtn"/>
<div id="noneReactiveDiv">{{ noneReactiveVariable }}</div>
</template>
In this case, clicking the button does not cause any change to the noneReactiveVariable in the template. Despite this, the console log within the nextTick function indicates that the UI or template has indeed been updated. The discrepancy between the behaviors raises the question of why noneReactiveVariable doesn't reflect a change in the template post-update like it did before when reactiveVariable was modified.
Update: After making slight adjustments to the code structure, the noneReactiveVariable is now being altered by a different function than the one affecting reactiveVariable. Surprisingly, even in this scenario, the noneReactiveVariable continues to be updated and reflected in the DOM upon clicking the button.
<template>
<input type="button" value="click" @click="clickBtn"/>
<div id="reactiveDiv">{{ reactiveVariable }}</div>
<div id="noneReactiveDiv">{{ noneReactiveVariable }}</div>
</template>
<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue"
const reactiveVariable = ref('reactive')
let noneReactiveVariable = 'non reactive '
onMounted(()=>{
setInterval(()=>{
noneReactiveVariable = (new Date().getTime()).toString()
},1000)
})
function clickBtn(){
reactiveVariable.value = (new Date().getTime()).toString()
nextTick(()=>{
console.log('next tick')
})
}
</script>