Vue js невозможно соединить элемент из вложенного v-for - PullRequest
1 голос
/ 27 мая 2020

Я начинаю с Vue. js и читал примерно splice() в соответствии с идентификатором / индексом элемента. Он отлично работает, если я пытаюсь splice() элемент в "турах" v-for:

data:{
   tours: null,
},
methods: {
  deleteTour: function (id) {
    if (confirm('Are you sure?')) {
        const index = this.tours.findIndex(item => item.id === id);
      if (~index) {
         axios.post('deleteTour.php', { "token": token, "tourID": id }).then((response) => {
           this.deleted = response;
           console.log(this.deleted);

           // splice tour
           this.tours.splice(index, 1);
         }).catch((error) => {
           this.errored = error;
           console.log(this.errored);
         });
       }
    }
  },
}

html

<div id="app" class="row mb-50">
   <div v-for="(item, index) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, index) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, index)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>

Но я не могу splice() элемент списка во вложенном v-for. Я пробовал использовать ref разными способами, но это не сработало.

deleteImage: function (id, tourID, index) {
   if (confirm('Are you sure?')) {

      // it could be done here
      this.$refs.deleteItem.splice(index, 1);

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},

Я хочу удалить весь первый элемент списка, содержащий значок значка. Возможно ли это?

Ответы [ 2 ]

1 голос
/ 28 мая 2020

Если мы используем разные имена переменных для индексов v-for в шаблоне, мы можем ссылаться на эти разностные индексы в deleteImage:

<div id="app" class="row mb-50">
   <div v-for="(item, indexItem) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, indexImage) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, indexItem, indexImage)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>

Затем в deleteImage:

deleteImage: function (id, tourID, indexItem, indexImage) {
   if (confirm('Are you sure?')) {

      // it could be done here
      // this.$refs.deleteItem.splice(index, 1);
      this.tours[indexItem].images.splice(indexImage,1)

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},

В общем, $refs не идеальное решение согласно документации Vue :

$ refs заполняются только после того, как компонент был отрисован, и они не реагируют. Он предназначен только как аварийный выход для прямых манипуляций с дочерними элементами - вам следует избегать доступа к $ refs из шаблонов или вычисленных свойств.

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

На основе комментария Катона Минора. Я изменил

deleteImage: function (id, tourID, index) {
    this.$refs.deleteItem.splice(index, 1);

на:

deleteImage: function (id, tourID, i, index) {
    this.tours[index].images.splice(i, 1);

, где i - это индекс изображения из <li v-for="(image, i) in item.images", а index - индекс тура от <div v-for="(item, index) in tours"

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