我正在 Axios API 调用中填充表格,并且需要向每一行添加一个删除按钮。
根据我目前的经验,我不太确定如何处理这个问题:
formattedVehicles.push([
"<div class='btn btn-danger' v-on:click='deleteVehicle(id)'>Delete</div>"
]);
当然,这是行不通的。如何获取删除按钮的点击处理程序以获取参数并将其作为方法处理?
最佳答案
在 Vue.js 中,您不必像 jQuery 那样创建 div。
这里有一系列车辆。当数组改变时,模板将会更新。
您只需要像这样管理车辆数组:
new Vue({
el: "#app",
data: function() {
return {
formattedVehicles: [
{ id: 1, name: 'vehi1' },
{ id: 2, name: 'vehi2' },
{ id: 3, name: 'vehi3' }
]
}
},
methods: {
callingAxiosApi: function() {
//---> Inside your '.then(function (response) {' you do:
//---> this.formattedVehicles = response; If response is the array of vehicles
},
addVehicle: function() {
var rand = Math.floor(Math.random() * (100 - 4)) + 4;
this.formattedVehicles.push({ id: rand, name: 'vehi' + rand });
},
deleteVehicle: function(id, index) {
//---> Here you can use 'id' to do an Axios API call.
this.formattedVehicles.splice(index, 1);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="app">
<button @click="addVehicle">Add vehicle</button>
<div v-for="(vehicle, index) in formattedVehicles" :key="index">
id: {{ vehicle.id }}
<br />
name: {{ vehicle.name }}
<button @click="deleteVehicle(vehicle.id, index)">Delete this vehicle</button>
</div>
</div>
要理解上面的代码:
使用v-for
当您有一个要在 html 中显示的列表时:
v-for="(anyNameYouWantForItemOfArray, index) in yourArray"
div
内包含 v-for
您可以访问数组的项目:{{ vehicle.id }}
, {{ vehicle.name }}
或在事件处理程序中传递数据:@click="deleteVehicle(vehicle.id, index)"
您必须使用key
属性(property) v-for
自版本 2.2.0+ key :
In 2.2.0+, when using v-for with a component, a key is now required.
要添加事件处理程序,您只需输入 v-on:click="method"
或快捷方式 @click="method"
在本例中,我们输入 <button @click="deleteVehicle(vehicle.id, index)">Delete this vehicle</button>
在 v-for
所以当我们点击按钮时,我们调用 deleteVehicle
方法与行的索引。在您的情况下,您可以使用 id 与 axios 进行 API 调用。
我们使用v-bind
将 javascript 代码放入 html 属性中的指令 v-bind :
我们在v-for
所以我们可以访问index
多变的 :
v-bind:key="index"
或使用快捷方式“:”(冒号)::key="index"
关于javascript - Vue JS,为 JS 中创建的元素添加事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241152/