Last active
August 27, 2021 08:48
-
-
Save CMCDragonkai/9f1d27b030e19cedf082e8eb312cc0fc to your computer and use it in GitHub Desktop.
Vue 3 Reactivity #vue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<button @click="counter += 1">{{ counter }}</button> | |
</template> | |
<script lang="ts"> | |
import { defineComponent, ref } from 'vue'; | |
export default defineComponent({ | |
setup () { | |
// by using ref, the counter becomes a proxy | |
// now instead of passing by value, we are passing by reference the proxy object | |
// now when counter is incremented in the template and in the setup | |
// they will proxy to the same base numeric value | |
// thus our console.log in the setInterval and the template rendering updates the same | |
const counter = ref(0); | |
setTimeout( | |
() => { | |
counter.value += 1; | |
}, | |
1000 | |
); | |
setInterval( | |
() => { | |
console.log(counter.value); | |
}, | |
1000 | |
); | |
return { | |
counter | |
}; | |
} | |
}) | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<button @click="counter += 1">{{ counter }}</button> | |
</template> | |
<script lang="ts"> | |
import { defineComponent } from 'vue'; | |
export default defineComponent({ | |
setup () { | |
// note that counter here doesn't get updated | |
// even though the template @click handler is incrementing the counter | |
// this code results in 2 copies of counter, one in the setup scope | |
// one in the template scope | |
// so the template's counter does update cause the template counter increases | |
// but when setup's counter increments, this does not cause the template to re-render | |
let counter = 0; | |
setTimeout( | |
() => { | |
counter += 1000; | |
}, | |
1000 | |
); | |
setInterval( | |
() => { | |
console.log(counter); | |
}, | |
1000 | |
); | |
return { | |
counter | |
}; | |
}, | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This means by default Vue
setup
totemplate
is a "pass-by-value".