Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a exported variable reactive in Vue 3 / Nuxt 3?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://stackblitz.com/edit/nuxt-using-hooks-in-script-setup-g4pctr?file=components%2FMyComponent.vue

  • 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading