簡體   English   中英

如何在文本字段上使用 Vue3 + TypeScript v-model? “錯誤:無效的分配目標”

[英]How do I use Vue3 + TypeScript v-model on textfield? "ERROR: Invalid assignment target"

完整錯誤:

[plugin:vite:vue] Transform failed with 1 error:
/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73: 
ERROR: Invalid assignment target

"/home/projects/vue3-vite-typescript-starter-jkcbyx/src/App.vue:33:73"

Invalid assignment target
31 |        ? (_openBlock(), _createElementBlock("div", _hoisted_2, [
32 |            _withDirectives(_createElementVNode("textarea", {
33 |              "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (($setup.np?.description) = $event))
   |                                                                           ^
34 |            }, null, 512 /* NEED_PATCH */), [
35 |              [

這是App.vue

<script setup lang="ts">
import { ref } from 'vue'

interface Thing {
  description: string
}

const np = ref<Thing>({
  description: 'asdf asdf asdf',
})
</script>

<template>
  {{ np?.description }}
  <br />
  <textarea v-model.trim="np?.description"></textarea>
</template>

這里是錯誤的完整重現:


感謝這里的任何幫助 <3
這個問題比較費解。

您不能將雙重綁定 ( v-model ) 與可選鏈接 ( np?.description ) 一起使用。 雙重綁定意味着 getter & setter。 np為假時,您希望設置器設置什么? 我知道您將它包裝在v-if中,但可選鏈接告訴v-model目標 object 結構可能是undefined ,這是一個無效的賦值目標。

go 關於它的一種方法是創建一個計算description ,您可以在其中指定當np的當前值允許時如何設置np.description

const description = computed({
  get() {
    return np.value?.description || ''
  },
  set(description) {
    if (typeof np.value?.description === 'string') {
      np.value = { ...np.value, description }
    }
  },
})

看到它在這里工作: https://stackblitz.com/edit/vue3-vite-typescript-starter-wrvbqw?file=src%2FApp.vue


以上是一個非常通用的解決方案(當您確實需要使用帶有v-model可選鏈接時)。
在您的情況下,一個更簡單的選擇(可能是因為您將<textarea>包裝在v-if="np"中)根本不使用帶有v-model的可選鏈接:
v-model.trim="np?.description"替換為v-model.trim="np.description"

它會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM