Nuxt.js、Vuetify、Vuexを用いてWebアプリを制作しております。
複数のユーザー名が表示されている画面があり、ユーザー名をクリックしたらダイアログが開いてユーザー名を編集できるようになっております。
ダイアログにはキャンセルボタンと保存ボタンがあり、ユーザー名を編集した後でもキャンセルボタンを押すと元のユーザー名に戻ります。
上記のようなアプリを作ろうと思い以下のコードを書いてみたのですが、ユーザー名をクリックした際にダイアログ上に表示されるユーザー名がおかしいです。
例えばAさん、Bさん、Cさんの3ユーザーがいる場合、最初のユーザー(Aさん)をクリックした際にはどのユーザー名も表示されておらず、次にBさんをクリックするとAさんの名前が表示されます。またその次にCさんの名前をクリックするとBさんの名前が表示されるなど1つずつずれて表示されてしまいます。
ただダイアログが開いたときに表示される名前はずれているのですが、保存した際にはきちんと編集したかったユーザーが編集されています。(Bさんの名前をクリックしてAさんの名前が表示された場合でも、保存ボタンを押したらBさんの名前が変わります。)
おそらくDialog.vue
のmounted
部分に問題があるのではないかと思うのですがどうしたら良いか全く見当もつきません。
原因がお分かりの方がおられましたらご教授願えませんでしょうか?
何卒よろしくお願い致します。
vue
1// index.vue 2<template> 3 <div> 4 <v-card 5 v-for="(user, index) in $store.getters.getUsers" 6 :key="index" 7 > 8 <v-card-title> 9 <span 10 @click=";(selectedUser = user), $store.commit('toggleDialog')" 11 > 12 {{ user.name }} 13 </span> 14 </v-card-title> 15 </v-card> 16 17 <!-- ダイアログ --> 18 <Dialog :selectedUser="selectedUser" /> 19 </div> 20</template> 21 22<script> 23import Dialog from '~/components/Dialog.vue' 24 25export default { 26 components: { 27 Dialog 28 }, 29 data() { 30 return { 31 selectedUser: null // クリックしたユーザーのオブジェクトを格納 32 } 33 }, 34 // Storeにユーザーデータを保存 35 async fetch({ store, app }) { 36 const users = await app.$axios.$get('/api/v1/users') 37 store.commit('setUsers', users.data) 38 } 39} 40</script>
vue
1// components/Dialog.vue 2<template> 3 <v-dialog persistent v-model="$store.state.dialog"> 4 <v-card> 5 <v-card-text> 6 <v-text-field v-model="newName" label="名前" /> 7 </v-card-text> 8 9 <v-card-actions> 10 <v-btn @click="cancel()"> 11 キャンセル 12 </v-btn> 13 <v-btn @click="updateUser(selectedUser)"> 14 保存 15 </v-btn> 16 </v-card-actions> 17 </v-card> 18 </v-dialog> 19</template> 20 21<script> 22export default { 23 props: ['selectedUser'], 24 data() { 25 return { newName: null } 26 }, 27 mounted() { 28 this.newName = this.selectedUser.name 29 }, 30 methods: { 31 // リストを更新 32 updateUser(user) { 33 const data = { 34 name: this.newName 35 } 36 this.$axios 37 .$put(`/api/v1/users/${user.id}`, data) 38 .then((res) => { 39 this.$store.commit('updateUser', res.data) // ユーザー情報をアップデート 40 this.$store.commit('toggleDialog') // ダイアログを閉じる 41 }) 42 .catch((error) => { 43 console.log(error) 44 }) 45 }, 46 cancel() { 47 this.$store.commit('toggleDialog') 48 } 49 } 50} 51</script>
js
1// store/index.js 2 3export const state = () => ({ 4 users: [], 5 dialog: false 6}) 7 8export const getters = { 9 getUsers(state) { 10 return state.users 11 } 12} 13 14export const mutations = { 15 setUsers(state, payload) { 16 state.users = payload 17 }, 18 updateUser(state, payload) { 19 state.users.some((el, i) => { 20 if (el.id === payload.id) { 21 el.name = payload.name 22 } 23 }) 24 }, 25 toggleDialog(state) { 26 state.dialog = !state.dialog 27 } 28} 29
あなたの回答
tips
プレビュー