我目前有以下组件,我想做的是将api中的数据加载到我的模态中。数据正在按预期加载,但是模式仅在第二次单击时打开。第一次单击未打开模态。但是,当模态打开然后关闭时。全部重新打开。但是当我刷新时它不会打开。
<template>
<div>
<tbody v-for="(value, key) in users" :key="key.id">
<tr>
<td>{{ value.type }}</td>
</tr>
<tr v-for="user in value.user" :key="user.id">
<td class='text-center'>
<button class="btn btn-default" @click="edit(user.id)" data-toggle="modal" data-target="#modalEdit">
<i class="far fa-edit"></i> Edit
</button>
</td>
</tr>
</tbody>
<edit-modal
v-if="showEdit"
:info="info"/>
</div>
</template>
<script>
import EditModal from './EditModal.vue';
export default {
components: {
EditModal
},
data() {
return {
showEdit: false,
users: [],
info: {
name: '',
status: '',
}
}
},
methods: {
edit(userId) {
axios.get(`user/${userId}`)
.then(response => {
this.info = response.data
this.showEdit = true
}).catch(error => {
console.log(error)
})
}
}
}
</script>
<template>
<div>
<div class="modal fade" id="modalEdit">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header bg-primary">
<h6 class="modal-title text-white font-weight-bold">Edit</h6>
<div class="cursor-pointer" data-dismiss="modal" title="Close">
<i class="fas fa-times text-white"></i>
</div>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-sm-4">User</label>
<div class="col-md-8">{{ info.name }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
info: {
type: Object,
default: () => ({
name: '',
status: '',
})
}
}
}
</script>
奇怪的是,如果我在编辑方法中删除了axios请求
methods: {
edit(userId) {
this.showEdit = true
}
}
模态从第一次点击开始。但是我需要axios请求来填充模态中的数据。
答案 0 :(得分:0)
您无需在此处写return true
methods: {
edit(userId) {
axios.get(`user/${userId}`)
.then(response => {
this.info = response.data
this.showEdit = true
}).catch(error => {
console.log(error)
})
}
}
这应该有效。
答案 1 :(得分:0)
第一次单击可能不起作用,因为如果您使用v,则在条件为真之前dom中不存在该组件。在这种情况下,直到this.showEdit为true时,按钮data-target和data-toggle才存在。
第一次单击按钮this.showEdit直到获得响应才为false,第二次单击按钮this.showEdit为true,因为您早已获得响应,但在获得响应之前数据可能已过时。第二反应。
我将使用的解决方案是在单击时将showEdit设置为true,然后将prop作为用户名传递给用户模态,并在模态组件的就绪/安装挂钩上获取数据,然后填写您的信息。
顺便说一句,我认为您的按钮数据目标和模式ID应该匹配。
答案 2 :(得分:0)
您尝试使用“ v-show”代替
<edit-modal
v-show="showEdit"
:info="info"/>