Home  >  Q&A  >  body text

How to use Vue3 + TypeScript v-model on text field? "Error: Invalid allocation target"

Completely wrong:

[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 |              [

This is 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>

Here is a complete reproduction of the error:


Thanks for any help here <3

This question is rather confusing.

P粉343408929P粉343408929297 days ago452

reply all(1)I'll reply

  • P粉729436537

    P粉7294365372023-12-28 00:23:57

    You cannot use double binding (v-model) with optional linking (np?.description). Double binding means getter and setter. What do you want the setter to set when np is false? I know you're wrapping it in a v-if , but the optional linkage tells v-model that the target object structure may be undefined, which is an invalid assignment target.

    One approach is to create a calculated description where you specify how to set np.description when the current value of np > allows:

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

    See how it works here: https://stackblitz.com/edit/vue3-vite-typescript-starter-wrvbqw?file=src/App.vue


    The above is a very general solution (when you actually really need to use the optional linkage of v-model).
    In your case, a simpler alternative (probably because you wrap