更新另一个函数中的 v-model 变量

huangapple go评论49阅读模式
英文:

Update v-model variable in another function

问题

这可能是一个非常简单的问题,但在搜索了几个小时后,我没有找到任何有用的信息。考虑以下代码:

<script setup>
var code = 123;

function run() {
    code = 5456;
}
</script>

<template>
    <input v-model="code" /> <button @click="run">Run</button>
</template>

当我点击按钮时,输入框中显示的值没有改变。

我尝试了使用 ref,但它不起作用。

英文:

This maybe a very simple problem, but I didn't find any useful information after searching for some hours. Consider the following code:

&lt;script setup&gt;
var code = 123;

function run() {
    code = 5456;
}
&lt;/script&gt;

&lt;template&gt;
    &lt;input v-model=&quot;code&quot; /&gt; &lt;button @click=&quot;run&quot;&gt;Run&lt;/button&gt;
&lt;/template&gt;

When I click button, the value shown in input is not changed.

I tried ref which doesn't work.

答案1

得分: 1

Ref works - try this code:

<script setup>
import { ref } from 'vue'

var code = ref(123);

function run() {
    code.value = 5456;
}
</script>

<template>
    <input v-model="code" /> <button @click="run">Run</button>
</template>

You can confirm it here on Vue Playground

英文:

Ref works - try this code:

&lt;script setup&gt;
import { ref } from &#39;vue&#39;

var code = ref(123);

function run() {
    code.value = 5456;
}
&lt;/script&gt;

&lt;template&gt;
    &lt;input v-model=&quot;code&quot; /&gt; &lt;button @click=&quot;run&quot;&gt;Run&lt;/button&gt;
&lt;/template&gt;

You can confirm it here on Vue Playground

huangapple
  • 本文由 发表于 2023年5月7日 01:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定