英文:
I want to update the reactive values of Vue.js 3 using a method written in an external file
问题
Sure, here's the translated content:
我想要使用在外部文件中定义的方法来更新 Vue.js 3 的响应式值。
(例如)
我正在学习 Vue.js 3。首先,我想要将响应式值传递给在外部文件中定义的方法,并更新这些值。
我创建了一个用于测试的计数组件。在 increment1 方法中,值会得到更新(屏幕上的数字会增加),但在 increment2 方法中,值不会得到更新。需要做哪些修改来在 increment2 方法中更新值?
相关源代码
<script setup lang="ts">
import { Ref, ref } from 'vue';
import { increment as increment2 } from './increment';
const count = ref(0);
const increment1 = () => {
count.value++;
}
</script>
<template>
<main>
<p>计数器数值</p>
<p>{{ count }}</p>
<button @click="increment1()">操作1</button>
<button @click="increment2(count)">操作2</button>
</main>
</template>
export const increment = (count: number) => {
count++;
}
FW/工具版本:
Vue.js 3.2.27
TypeScript 4.7.4
英文:
I want to update the reactive values of Vue.js 3 using a method defined in an external file.
(e.g.)
I am studying Vue.js 3. First, I want to pass reactive values to a method defined in an external file and update the values.
I created a count component for testing purposes. In the increment1 method, the value gets updated (the number on the screen increases), but in the increment2 method, the value does not get updated. What modifications are necessary to update the value in the increment2 method?
Relevant Source Code
<script setup lang="ts">
import { Ref, ref } from 'vue';
import { increment as increment2 } from './increment';
const count = ref(0);
const increment1 = () => {
count.value++;
}
</script>
<template>
<main>
<p>Counter Value</p>
<p>{{ count }}</p>
\ <button @click="increment1()">Action1</button>
\ <button @click="increment2(count)">Action2</button>
</main>
</template>
export const increment = (count: number) => {
count++;
}
FW/Tool versions:
Vue.js 3.2.27
TypeScript 4.7.4
答案1
得分: 1
在模板中使用时,"Refs"会自动解包,这意味着你的代码行
@click="increment2(count)"
等同于
@click="increment2(count.value)"
这不是响应式的。你想要做的是在你的<script>
标签内发送实际的count
引用,只有这样才能实现。
import { increment } from "./increment.js";
const increment2 = () => {
increment(count);
};
<button @click="increment2">Action2</button>
英文:
Refs when used in the template are automatically unwrapped, meaning your line
@click="increment2(count)"
is equivalent to
@click="increment2(count.value)"
Which is not reactive. What you want to do is send the actual count ref, which can only be done within your <script>
tag
import { increment } from "./increment.js";
const increment2 = () => {
increment(count);
};
<button @click="increment2">Action2</button>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论