Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

v-model cannot be used on v-for

Tags:

eslint

vuejs3

VueCompilerError: v-model cannot be used on v-for or v-slot scope variables because they are not writable. Why?

<template>
  <div v-for="service in services" :key="service.id">
    <ServicesItem v-model="service"></ServicesItem >
  </div>
</template>
<script lang="ts">
import ServicesItem from "@js/components/ServicesItem.vue"

export default defineComponent({
  components: { ServicesItem },
  setup() {
    const services = ref([
      {
        id: 1,
        name: "Service 1",
        active: false,
        types_cars: {
          cars: {},
          suv: {},
        },
      },
    ])

    return {
      services,
    }
  },
})
</script>

What are the best practices? Reactive object transfers

like image 200
Goryyn Avatar asked Sep 13 '25 12:09

Goryyn


2 Answers

Okay, so what's going on is that the variable "service" is, let's say, virtual. It doesn't exist, it's just a part of your real object "services" at a certain point (iteration).

If you'd like to "attach" that iteration to your component, you need to provide a real object, and in your case that would be done like that:

<div v-for="(service, i) in services" :key="service.id">
    <ServicesItem v-model="services[i]"></ServicesItem >
</div>
like image 183
aymcg31 Avatar answered Sep 16 '25 09:09

aymcg31


Same issue here, i've change the modelValue props by an other custom props, and it works fine for me. old:

const props = defineProps({
    modelValue: {
        type: Object,
        required: true
    }
})

NEW:

const props = defineProps({
    field: {
        type: Object,
        required: true
    }
})

Component: <MyComponent :field="service"/>

instead of <MyComponent :v-model="service"/>

like image 42
user3190147 Avatar answered Sep 16 '25 07:09

user3190147