0

I have an array in my Vuex store called Projects. I want to loop through these projects and default to the first item. I have setup a v-model on this select input so I can use the chosen result in my local component.

I read on this SO how I can use v-modal to do this.

However because I populate via Vuex store I think I need to do differently.

So I made my Vuex action I call a promise so in my component I can determine when it has resolved, so I can then populate my local component data (and thus the select input).

loadData: ({ commit }, payload) => {
  return new Promise((resolve, reject) => {
    // get projects on load
    axios
      .get("/api/projects/")
      .then(function(response) {
        commit("updateProjects", response.data);
        resolve();
      })
      .catch(function(error) {
        // handle error
        throw error;
      });
  });
};

Then in my local component I have the following triggered on created():

created() {
  this.$store
    .dispatch("loadData")
    .then((this.modalCreate.project = this.projects)); // dispatch loading
}

And within my component I have the following:

<select class="form-control" v-model="modalCreate.project">
  <option
    v-for="(project, index) in projects"
    :value="project"
    :key="project.id"
  >
    {{ project.name }}
  </option>
</select>

In the above I have used mapState to map my store.projects to local projects.

In this setup I can see the select options populated from the local projects (from Vuex) but I cannot get the select form to default to the first index.

I suspect this is because I have not correctly made my modalCreate.project the first store.project object. Currently my modalCreate.project is undefined.

Most grateful for any advice on how to best achieve this and whether mapping Vuex state to local state is over-engineering a solution.

--

Perhaps this cloning solution can be applied? I had no luck though: SO Link

1
  • Your <option /> should have a selected attribute on the first index. E.g. <option :selected={ somethingSelectedHere || index === 0 }/> Commented Jun 22, 2019 at 15:07

1 Answer 1

0

I suppose you want to select the first project (index === 0) as your default project:

created() {
  this.$store
    .dispatch("loadData")
    .then(() => {
        this.modelCreate = {
            ...this.modelCreate,
            project: this.projects[0]
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

this.modalCreate.project not populating, but I can console.log(this.projects[0]); and see that the correct project object is being returned.... Feel like we're nearly there...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.