Selected options in vuejs

Viewed 61

I have edit form and I need to get selected options from database to be selected by default when page loads.

Logic

  1. Get post data (done)
  2. Get all tags (done)
  3. Get post tags (done)
  4. Select post tags from tags list by default (need help)

Code

HTML

<vs-select
    :key="tags.length"
    filter
    :label="$t('posts.tags')"
    v-model="form.tags"
    multiple
    state="success"
>
    <vs-option
        v-for="tag in tags"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
    >
        {{ tag.name }}
    </vs-option>
</vs-select>

Script

data() {
    return {
      tags: [], // all tags
      form: {
        tags: [], // post tags
      },
    };
},
mounted() {
    this.fetchPost(); // get post data including it's tags
    this.fetchTags(); // get all tags
},
methods: {
    fetchPost() {
      axios
        .get("/api/admin/posts/" + this.$route.params.id, {
            headers: {
                Authorization: localStorage.getItem("access_token"),
            },
        })
        .then((response) => {
            //....
            this.form.tags = response.data.data.tags;
        })
        .catch(function (error) {
          console.log("error", error);
        });
    },
    fetchTags() {
      axios
        .get("/api/admin/tags", {
            headers: {
                    Authorization: localStorage.getItem("access_token"),
            },
        })
        .then((response) => {
            this.tags = response.data.data;
        })
        .catch(function (error) {
            console.log("error", error);
        });
    },
},

Any idea?

1 Answers

I've changed my fetching code to the following line and it's working now

this.form.tags = response.data.data.tags.map((x) => x.id);
Related