[Vuejs]-How can I bind v-model to data () when I am v-binding to selected option in select tag in vue

0👍

BY BINDING VALUE

<template>
  <div>
    <select v-model="selected" class="border py-2 px-3 text-grey-800 w-full" name="contact_id">
      <option
        v-for="contact in contacts"
        :key="contact.id"
        :value="contact.id"
      >{{contact.name}}</option>
    </select>
  </div>
</template>

USING COMPUTED PROPERTIES

<template>
  <div>
    <select v-model="selected" class="border py-2 px-3 text-grey-800 w-full" name="contact_id">
      <option v-for="contact in contacts" :key="contact.id">{{contact.name}}</option>
    </select>
  </div>
</template>

Selected is an object so you can initialize it like it:

 data() {
    return {
      name: "",
      selected: {},
      activity_type_id: "",
      comments: "",
    };
  },

You can use a computed property to get the id:

 computed: {
    selectedID: function () {
      return this.selected.id;
    },
  }

And the method becomes:

  methods: {
    addActivity() {
      let activityAdd = {
        comments: this.comments,
        contact_id: this.selectedID,
        activity_type_id: this.activity_type_id,
      };
      this.$inertia.post("/activity", activityAdd);
    },
  },

Leave a comment