Search code examples
ionic-frameworkvuejs3vuexpinia

Update v-model from state from store


I have an input field component that i am trying to reset whenever the field loses focus or whenever the user presses the Escape button. However the v-model that comes from a store state is never updated, why is that? Also is this the correct way to deal with input components?

Input child component:

<template>
 <ion-input
  placeholder="Name"
  :modelValue="modelValue"
  @ionInput="editedName= $event.target.value;"
  @ion-focus="currentName = modelValue"
  @keydown.esc="$emit('update:modelValue', currentName )"
  @ion-blur="$emit('update:modelValue', currentName )"
/>
</template>
<script setup lang="ts">
import {IonInput} from "@ionic/vue";
import { onBeforeMount, ref } from "vue";
  
interface Props {
  id: string;
  modelValue: string;
}
const props = defineProps<Props>();

const currentName = ref();
const editedName= ref();
const edit = ref(false)
</script>

And this is how how i use it on my parent component:

<template>
 <ItemField
  :id="data.id"
  v-model="data.name"
 />
</template>
<script setup lang="ts">
import ItemField from '@/components/admin/ItemField.vue'
import {myStore} from '@/stores/myStore'
import { storeToRefs } from 'pinia'
import { spaceType } from "@/types";

const store = myStore()
const { data} = storeToRefs(store );
</script>

What exactly am i doing wrong?


Solution

  • First, :modelValue isn't a property according to the ionic docs, it should be :value

    <ion-input
      :value="modelValue"
    />
    

    Second, change your @input event to update the modelValue which will update the store data.name value. The emits from @keydown.esc and @blur should do their job of resetting data.name to the previous value

    <template>
      <ion-input
        placeholder="Name"
        :value="modelValue"
        @input="$emit('update:modelValue', $event.target.value)"
        @focus="currentName = modelValue"
        @keydown.esc="$emit('update:modelValue', currentName)"
        @blur="$emit('update:modelValue', currentName)"
      />
    </template>
    <script setup lang="ts">
    import { IonInput } from "@ionic/vue";
    import { ref } from 'vue'
    
    interface Props {
      id: string
      modelValue: string
    }
    defineProps<Props>()
    defineEmits(['update:modelValue'])
    
    const currentName = ref('')
    </script>