Using binded V-model variable in composition API Method

When I try to access text from an input field using v-model when saving information with options API, it works great, but I can’t get it to work on composition API.
I get a name on my student list with the options code, but I only get a blank empty string with the composition API, I’m not getting the value from the v-model binding.

HTML section:

<template>
  <base-layout page-title="Add Student" page-default-back-link="/studentList">
    <form class="ion-padding" @submit.prevent="submitForm">
      <ion-list>
        <ion-item>
          <ion-label position="floating">Name</ion-label>
          <ion-input type="text" required />
        </ion-item>
        <ion-item>
          <ion-label position="floating"
            >Student ID (unique identifier)</ion-label>
          <ion-input type="text" required v-model="enteredStudentId" />
        </ion-item>
      </ion-list>
      <ion-button type="submit" expand="block">Save</ion-button>
    </form>
  </base-layout>
</template>

Working Options code:

export default {
  components: {
    IonList,
    IonItem,
    IonLabel,
    IonInput,
    IonTextarea,
    IonButton, //may want to make it a global component
  },
  data() {
    return {
      enteredStudentId: "",
    };
  },
  methods: {
    saveStudent(studentData) {
      this.$store.dispatch('addStudent', studentData);
      this.$router.replace('/studentList');
    },
    submitForm() {
      const studentData = {
        id: this.enteredStudentId,
      };
      this.saveStudent(studentData);
    },
  },

Composition code that only give me an empty string back

import { useStore } from "vuex";
import { useRouter,  } from "vue-router";
import { ref } from '@vue/reactivity';

name: "VModel",

  setup() {
    const store = useStore();
    const router = useRouter()

    var enteredStudentId = ref('');

    const saveStudent = (studentData) => {
      store.dispatch("addStudent", studentData);
      router.replace('/studentList');
    };

    const submitForm = () => {
        const studentData = {
            id: enteredStudentId.value,
        }
           saveStudent(studentData);
    }
    return { saveStudent, submitForm }
  },
};

enteredStudentId isn’t part of your return so the template doesn’t know anything about it.

You need:

return {
  saveStudent,
  submitForm,
  enteredStudentId
}
1 Like

Thank you, I didn’t think that would matter since I thought the setup return would only affect things outside of it and didn’t think of it needing to return it for v-model to see it.