It's been only 2 weeks since I started working with Vue
, and so far, everything is going smoothly. However, I'm facing a challenge that I could use some help with.
I need to create a series of select inputs based on options retrieved from the database for user
preferences. Sometimes, the user
may have already made selections for some or all of these options.
The issue I'm encountering is that I can't figure out how to populate the generated select inputs with the user's current choices.
I had it working perfectly until I introduced auto-generation of the inputs. Below is my code snippet - any assistance provided would be greatly appreciated. If you require more information, please feel free to ask. I believe my objective is quite clear, but it appears that the Vue code is overwriting the values and rendering them blank during generation.
Code in the blade.php
<div class="form-group row" v-for="preference in preferences">
<label class="col-md-4 col-form-label text-md-right">
@{{ preference.name }}
<span v-if="currentPreferences[preference.id] && currentPreferences[preference.id].value">
<br /> (current: @{{ currentPreferences[preference.id].value }})
</span>
</label>
<div class="col-md-6">
<select class="form-control" @change="updatePreferences(preference)" v-model="selected[preference.id]">
<template v-if="currentPreferences[preference.id] && currentPreferences[preference.id].value">
<option disabled value="">Please select one</option>
<option v-for="item in preference.options" :value="item" :selected="item == currentPreferences[preference.id].value">@{{ item }}</option>
</template>
<template v-else>
<option disabled value="">Please select one</option>
<option v-for="item in preference.options" :value="item">@{{ item }}</option>
</template>
</select>
</div>
</div>
Code in hero-preferences.js
Vue.component('dashboard-preferences', {
props: ['user'],
data() {
return {
preferences: [],
currentPreferences: []
};
},
mounted() {
this.getPreferencesData();
},
methods: {
getPreferences() {
axios.get('/dashboard/preferences')
.then(response => {
this.preferences = JSON.parse(response.data);
})
.catch(response => {
this.preferences = [];
});
},
getCurrentPreferences() {
axios.get('/dashboard/preferences/current')
.then(response => {
this.currentPreferences = JSON.parse(response.data);
})
.catch(response => {
this.currentPreferences = [];
});
},
getPreferencesData() {
this.getPreferences();
this.getCurrentPreferences();
}
}
});
Code in email-preferences.js
(sub-component)
Vue.component('dashboard-hero-preferences-email-preferences', {
props: ['user','preferences','currentPreferences'],
data() {
return {
updated: null,
selected: [],
updatePreference: null
};
},
methods: {
updatePreferences(preference) {
this.updatePreference = preference;
axios.post('/dashboard/preferences/update', {
preference: preference.id,
value: this.selected[preference.id]
})
.then(() => {
this.$emit('update');
this.updated = 'yes';
});
}
}
});
Thank you, David