首页 > 解决方案 > 如何使导出的变量在 Vue 组件中具有反应性?

问题描述

我有一个 js 文件,它导出一个变量并每秒增加它

let total = 0
setInterval(function() {
  total++
}, 1000)
export { total }

以及打印所述变量的 Vue 组件。

<template>
  <div id="app">
    {{ total }}
  </div>
</template>

<script>
  import {
    total,
  } from "./worker";
</script>

我怎样才能做出total反应?

标签: javascriptvue.js

解决方案


值类型是不可能的,因为值类型是按值传递的(值只是被复制的)。您需要的是传递对对象的引用...

counter.js

let counter = {
  total: 0
};
setInterval(function() {
  counter.total++;
}, 1000);
export default counter;
<template>
  <div>
    <h1>{{ counter.total }}</h1>
  </div>
</template>

<script>
import cnt from "@/counter";

export default {
  name: "HelloWorld",
  data() {
    return {
      counter: cnt
    };
  }
};
</script>

推荐阅读