How to use Vue3 + TypeScript v-model on text field? "Error: Invalid allocation target"
P粉343408929
P粉343408929 2023-12-27 08:57:28
0
1
521

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:

  • https://stackblitz.com/edit/vue3-vite-typescript-starter-jkcbyx?file=src/App.vue

Thanks for any help here <3

This question is rather confusing.

P粉343408929
P粉343408929

reply all(1)
P粉729436537

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 in v-if="np"), don't use Optional linkage for v -model root:
Replace v-model.trim="np?.description" with v-model.trim="np.description".

It will work.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template