Home > OS >  How to fix 'error invalid assignment target' vue 3
How to fix 'error invalid assignment target' vue 3

Time:12-27

I am building application using Vite and Quasar. I built a child component and defined the props and data and use them on template. But have this error: Invalid assignment target

<template>
  <QCheckbox 
    v-model="(data.gps?.enable)" 
     
    label="GPS Only Tracking Enabled " />
</template>

<script setup lang="ts">
  import Vue from "vue";
  import {defineComponent } from "vue";
  import * as types from "../../../types";
  
  const props = defineProps({
    modalProps: Object as () => types.Itarget
  });
  
  const defaults = {
      gps: props.modalProps?.gps,
  };
  let data = ref(_.cloneDeep(defaults));
</script>

Here, "gps" is object like this: gps: { enable: true, perform?: 'Normal', distance?: 33 }

If I use 'data.gps?.enable' on v-model, error has been occured. How to fix this??

CodePudding user response:

When you assign a value to data the component is not already mounted (or beforeMounted), so the component don't know at this moment the value of the props.

you should assign variables only in creation hooks

onBeforeMount(() => {
    defaults = {
        gps: props.modalProps?.gps,
    };
    data.value = _.cloneDeep(defaults)
})

if you want to be more secure you can add a v-if in your template and check if the value exists

<QCheckbox v-if="data.gps" .... >

Even better: default values for props

const props = withDefaults(defineProps<{
    modalProps: Object as () => types.Itarget
}>(), {
    modalProps: { enable: false, perform: '', distance: null }
})
  • Related