javascript - 如何使导出的变量在 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
反应?
解决方案
值类型是不可能的,因为值类型是按值传递的(值只是被复制的)。您需要的是传递对对象的引用...
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>
推荐阅读
- node.js - 如何使用 api 在 google 表格中查找值,用于 Node JS
- ssas - MDX 聚合和 where 子句基础知识
- .net - 使用 windows api 获取 windows mp3 文件属性或标签?
- python - 在一维数组'a'中找到'a'的索引'a'='b',其中'b'是'a'的随机值
- php - 可以在PHP中导入魔术常量吗
- php - 迭代数组然后再次重置多个数组
- c# - 如何在主窗口中实现接口
- javascript - 如何将数据放入嵌套数组并将其绑定到 HTML Knockout.js
- c# - 如何创建一个唯一约束,该约束也允许使用流利的迁移器为空?
- javascript - CORS 策略阻止本地主机