4

So lets say i have a data - news: {id:3, name:"book", author:'author'}. And select with options: {id: 1, book: "book1"}, {id: 2, book: "book2"} .

Now i want to v-bind options with news.id and news.book Is there a way of doing it or ready component for this?

APlusPeace
  • 75
  • 1
  • 9

2 Answers2

5
<select v-model="selected">
  <option v-for="option in options" :value="option.id">
    {{ option.name}}
  </option>
</select>
  data() {
    return {
      selected: 1,
      options: [
        { name: 'book1', id: 1 },
        { name: 'book2', id: 2 },
        { name: 'book3', id: 3 }
      ]
    }
tauzN
  • 5,162
  • 2
  • 16
  • 21
  • Thats is how u can do an array of objects. Maybe I asked an inaccurate question. But can i bind this selected.name and selected.id to my model news so it would be reactive. So i dont need to address select in the end of operations to change my data. – APlusPeace Apr 04 '21 at 14:02
  • I am not sure what you mean. You can access the selected option name with this.options.find(option => option.id == this.selected).name. You should only have the "real" or "true" data at one place. – tauzN Apr 04 '21 at 19:41
2

So in the end i made this:

<select1
    :selected="{ id: book.id, name: book.name }"
    v-model:id="book.id"
    v-model:name="book.name"
    urldata="url/to/get/options"
></select1>

And my component look like this:

<template>
  <div>
    <select v-model="selected" @change="change" class="form-select">
      <option v-for="option in options" :value="option">
        {{ option.name }}
      </option>
    </select>
  </div>
</template>
export default {
  name: "select1",
  emits: ["update:selected", "update:id", "update:name"],
  props: {
    selected: Object,
    urldata: String,
  },
  data: function () {
    return {
      options: [],
    };
  },
  mounted() {
    this.GetListData();
  },
  methods: {
    GetListData() {
      if (this.urldata !== "") {
        axios
          .get(`${this.urldata}`)
          .then((response) => (this.options = response.data.results));
      }
    },
    change(event) {
      console.log(this.selected);

      this.$emit("update:selected", this.selected);
      this.$emit("update:id", this.selected.id);
      this.$emit("update:name", this.selected.name);
    },
  },
};
APlusPeace
  • 75
  • 1
  • 9