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

标签 javascript vue.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>

要理解上面的代码:

使用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/

相关文章:

javascript - 如何在 EJS 中从另一个文件调用 Javascript 函数

javascript - 使用带有 click() javascript 的函数

javascript - 输入上的 v-model 返回输入元素而不是值

javascript - 将变量从路线传递到 Blade View

vue.js - 在 vue 生命周期钩子(Hook)中延迟销毁

javascript - 解析 JSON 响应时出现问题

javascript - 我如何更改网页源包括(html、css、js)geckofx c#

javascript - 使用 MomentJS 引导 Datepicker Locale

javascript - TypeError : Cannot read property 'clipboard' of undefined when calling this. $ q.electron.clipboard

vue.js - Vue-JS v-show Percitence in radio