I can’t understand how I can make a exported variable from a script reactive in the template section.
I have followed this Vue 2 stackoverflow question, but it doesn’t work for me.
Demo
Here is a simple demo on stackblitz:
- script:
/assets/functions/test.js - component:
/components/myComponent.vue
Code
// test.js
export let count = {
total: 0, // <-- make reactive in template
};
export const addCount = () => {
count.total++;
};
<script setup>
import { count, addCount } from '~/assets/functions/test';
import { ref } from 'vue';
const totalCount = ref(count);
</script>
<template>
<h1>{{ totalCount }}</h1>
<button @click="addCount()">Add+</button>
</template>
the count.totalonly updates after saving the vue-file / refresh the component.
Question
Any suggestions how I can make a exported variable reactive in a clean Vue 3 / Nuxt 3 way?
>Solution :
you have to make it a react proxy using react system (ref, shallowRef, reactive, shallowReactive, triggerRef…)
// test.js
import { reactive } from "vue"
export const count = reactive({
total: 0, // <-- make reactive in template
});
export const addCount = () => {
count.total++;
};
<script setup>
import { count, addCount } from '~/assets/functions/test';
import { computed } from 'vue';
const totalCount = computed(() => count.total)
</script>
<template>
<h1>{{ totalCount }}</h1>
<button @click="addCount()">Add+</button>
</template>