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
<option />should have aselectedattribute on the first index. E.g.<option :selected={ somethingSelectedHere || index === 0 }/>