如何在Vue 3 / Nuxt 3中使导出的变量具有React性?

jpfvwuh4  于 2023-04-21  发布在  Vue.js
关注(0)|答案(1)|浏览(161)

我不明白我怎么能让一个从脚本中导出的变量在模板部分起作用。
我有followed this Vue 2 stackoverflow question,但它不适合我。

Demo

以下是stackblitz上的一个简单演示:
https://stackblitz.com/edit/nuxt-using-hooks-in-script-setup-g4pctr?file=components%2FMyComponent.vue

  • 脚本:/assets/functions/test.js
  • 组件:/components/myComponent.vue

代码

// 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>

count.total仅在保存vue-file / refresh组件后更新。

提问

有什么建议可以让导出的变量以干净的Vue 3 / Nuxt 3方式响应?

w7t8yxp5

w7t8yxp51#

你必须使用React系统(refshallowRefreactiveshallowReactivetriggerRef ...)使其成为React代理。

// 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>

相关问题