Can someone explain how to properly utilize Vue3 + TypeScript's v-model with a textfield without encountering the error message: "Invalid assignment target"?

Complete Error Message:

[plugin:vite:vue] Transformation failed with one 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 the 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>

A Full reenactment of the error can be found here:


Any assistance would be greatly appreciated. Thank you!
This issue seems quite perplexing.

Answer №1

Dual-binding (v-model) cannot be used in conjunction with optional chaining (np?.description). Dual binding requires both a getter and setter function. If np is falsey, what value do you expect the setter to assign? Even if wrapped in a v-if, optional chaining implies that the target object structure for v-model may be undefined, making it an invalid assignment target.

An approach to address this issue is by creating a computed property for description, where you define how to handle setting

np.description</code when <code>np
's current value permits:

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

See an example implementation here: https://stackblitz.com/edit/vue3-vite-typescript-starter-wrvbqw?file=src%2FApp.vue


The above solution offers a general approach for situations where you genuinely need to combine optional chaining with v-model.
Alternatively, a simpler solution in your specific scenario (as you enclosed the <textarea> within v-if="np") is to avoid using optional chaining with

v-model</code entirely:<br />
Replace <code>v-model.trim="np?.description"
with
v-model.trim="np.description"
.

This adjustment should resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The object assigned in the Facebook login method cannot be utilized

I'm working on integrating Facebook login with Angular 2. Here's the button for logging in: <button ion-button (click)="fbLogin()"><ion-icon name="logo-facebook"></ion-icon>Login using Facebook</button> Below is the clic ...

Jest and Vue coverage reporting not functioning properly

During the unit testing of my Vue project using Jest, I encountered a problem where the HTML report for code coverage is not functioning as expected. Below are relevant snippets from my package.json and jest.conf.js files: package.json: ... "unit&quo ...

Binding images dynamically with Vue

I am looking to achieve something similar to this example, but with a slight change. Instead of directly using 'images.sample' as the parameter, I want to pass it through props like so: props:['images.sample'], <template> <img ...

Leverage Vue data within your stylesheet

Is there a way to access Vue data within my style sheet? I typically write in Sass, but I don't believe that is the root of the problem. The following attempt did not yield the desired results: #app background-color: {{ myText }} ...

PHALCON array entry now in place

Currently, I am facing an issue while trying to insert multiple data from an array. It seems that only the last piece of data is being inserted each time. Below is the front-end code snippet responsible for sending the data: let payload = new FormData(); ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

Making changes to a single formControl in angular6 will cause the other formControl to be updated as

I have two select menus in my user interface with the same options. When I select an option in one menu, I want the other menu to display the same option, and vice versa. Currently, I am using the valueChanges method on the first formControl to update the ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

PhpStorm flawlessly detects ES7 type hinting errors

For my project, I have implemented TypeScript. While JavaScript's array includes() function has been valid since ECMA6, setting the lib parameter in tsconfig to "es6" results in a non-fatal error being thrown in the browser console when using the foll ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Opening a file upon launching in Nativescript-Vue: A step-by-step guide

After following the steps outlined in this article, my app is successfully able to open a file with a simple click. Upon launching the application, I see the following message in my console.log: (Foundation) [com.apple.foundation.filecoordination:claims] ...

I'm facing an issue with Angular2 where I am unable to include a component from

I recently downloaded an angular component from npmjs called ng2-easy-table (I actually created this component, so there may have been some mistakes in its development). package.json { "name": "untitled", "version": "1.0.0", "description": "", "m ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

Troubleshooting Typescript & Express Routing Issue

I am currently following a tutorial on how to set up a simple express-typescript application. However, I am encountering some difficulties with my routes not working as expected. Despite searching for similar problems and solutions, I haven't found an ...

Material-UI - TypeScript - Autocomplete utilizing getOptionLabel and renderOption for optimized selection functionality

I am attempting to showcase member and company using MUI Autocomplete. I have an array called suggestion that contains the options to display. [ { "__typename": "Member", "id": "ckwa91sfy0sd241b4l8rek ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Running pre-commit eslint autofix but encountering errors that do not exist

Encountering an issue with committing changes to a file due to a failed pre-commit eslint --fix task, displaying the following errors: × eslint --fix: C:\Users\user\source\repos\project\project-frontend\src\compone ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...