Как я могу получить доступ к повторяющемуся ключу элемента из метода - PullRequest
0 голосов
/ 28 мая 2018

У меня есть html-страница, в которой есть таблица и повторяющаяся строка с использованием v-for:

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)">Delete</button>
    </td>
  </tr>
</table>

, и у меня есть этот код js.

var app4 = new Vue({
  el: '#app-4',
  data: {
    results: []
  },
  methods: {
    deleteItem: function (index) {
        this.results.splice(index,1);
        //Can I access item key and tr properties from here and the delete button
    }
  },
  mounted() {
    axios.get('api.list.url').then(response => {
        this.results = response.data;
    })
  }
});

В deleteItemМожно ли получить доступ к ключу элемента и tr свойств и добавить текст к кнопке удаления элемента.

1 Ответ

0 голосов
/ 28 мая 2018

Традиционный подход Vue, вероятно, будет использовать ссылки

<table id="app-4">
  <tr v-for="(item, index) in results" :key="item.id" ref="rows">
    <td>@{{ item.title }}</td>
    <td>
       <button v-on:click="deleteItem(index)" ref="deleteButtons>
           Delete
       </button>
    </td>
  </tr>
</table>

И в коде

deleteItem: function (index) {
    this.results.splice(index,1);
    //Can I access item key and tr properties from here?

    // Yes, e.g. to get the text content of the first cell
    const text = this.$refs.rows[index].cells[0].textContent.trim();

    // And add it to the delete button text
    this.$refs.deleteButtons[index].textContent += " " + text;
}

Конечно, этот пример немного бессмысленный, так как вы знаете название элемента, но принцип работает для других свойств текстовой строки (например, атрибуты, вычисляемые стили, классы и т. д.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...