Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active August 27, 2021 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/9f1d27b030e19cedf082e8eb312cc0fc to your computer and use it in GitHub Desktop.
Save CMCDragonkai/9f1d27b030e19cedf082e8eb312cc0fc to your computer and use it in GitHub Desktop.
Vue 3 Reactivity #vue
<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>
<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>
@CMCDragonkai
Copy link
Author

This means by default Vue setup to template is a "pass-by-value".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment