繁体   English   中英

Vue JS,为在 JS 中创建的元素添加事件处理程序

[英]Vue JS, add event handler for elements created within JS

我正在 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>

要理解上面的代码:

当您有要在 html 中显示的列表时使用v-for

v-for="(anyNameYouWantForItemOfArray, index) in yourArray"

在包含v-fordiv中,您可以访问 aray 的项目: {{ vehicle.id }}{{ vehicle.name }}或在事件处理程序中传递数据: @click="deleteVehicle(vehicle.id, index)"

从 2.2.0+ 版本开始,您必须在v-for中使用key属性key

在 2.2.0+ 中,当对组件使用 v-for 时,现在需要一个键。

要添加事件处理程序,您只需输入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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM