Попытка обновить DOM - PullRequest
0 голосов
/ 12 января 2019

Я, очевидно, попал в предостережение Vue.js, я полагаю. Тем не мение: Я отображаю список элементов (заметок) v-if и хочу поменять его, когда флажок установлен.

Я получаю данные из хранилища (Axios get) и немедленно назначаю их другому свойству (appNotes), чтобы потом ими можно было манипулировать. Я не могу получить заметки для обновления при первом рендере. Они делают, когда я проверяю флажок. Вот соответствующий код:

  <div class="form-check">
  <input type="checkbox" id="appNotes" class="form-check-input" @click="handleClick"
  v-model="check">
  <label for="appNotes" class="form-check-label" >Older Notes First</label>
  <!-- {{check? this.appNotes=[...this.notes].reverse():this.appNotes=this.notes}} -->
  <!-- This surprisingly reverses the notes and produces s warnig about inifinite loop -->
</div>
<section class="row text-center text-lg-left " v-if="notes.length">
  <NoteThumb 
  v-for="note in appNotes" 
  :key="note.id" 
  :note="note">
    <h4>{{ note.title }}</h4>
    <p>{{ note.date }}</p>
    <p>{{ note.id }}</p>
  </NoteThumb>
</section>


  data(){
    return {
      appNotes: {},
      check:false
  },
  handleClick(){
    this.check? this.appNotes=[...this.notes].reverse():this.appNotes=this.notes
  },
  passNotes(){
    this.$set(this.appNotes, this.notes, null)
    this.appNotes=null
    this.$forceUpdate()
  },
  async created (){
  await this.$store.dispatch('notes/getNotes')
  await this.passNotes()
  }

https://codesandbox.io/s/2jqr60xmjj это не рабочая ссылка, но вы можете увидеть полный код в компоненте 'Home'

Ответы [ 2 ]

0 голосов
/ 13 января 2019

Я бы предложил вам убрать @ click = "handleClick" и создать свойство watch для проверки. Таким образом, после загрузки асинхронного запроса вы можете установить проверку на false и затем она отобразит ваш список заметок.

<template>
<div class="form-check">
  <input type="checkbox" id="appNotes" class="form-check-input" v-model="check">
  <label for="appNotes" class="form-check-label" >Older Notes First</label>
  <!-- {{check? this.appNotes=[...this.notes].reverse():this.appNotes=this.notes}} -->
  <!-- This surprisingly reverses the notes and produces s warnig about inifinite loop -->
</div>
<section class="row text-center text-lg-left " v-if="notes.length">
  <NoteThumb 
  v-for="note in appNotes" 
  :key="note.id" 
  :note="note">
    <h4>{{ note.title }}</h4>
    <p>{{ note.date }}</p>
    <p>{{ note.id }}</p>
  </NoteThumb>
</section>
</template>
<script>
    export default {
        data() {
            return {
                appNotes: {},
                check:false
            };
        },
        methods:
        {
        passNotes(){
            this.$set(this.appNotes, this.notes, null)
            this.appNotes=null
            this.$forceUpdate()
            //here you can just set check to false and it will update the appNotes
            this.check = false
         },
        async created (){
            await this.$store.dispatch('notes/getNotes')
            await this.passNotes()
        }
        },
        watch: {
            check: function () {
                this.check? this.appNotes=[...this.notes].reverse():this.appNotes=this.notes
            }
        }

    }
</script>
0 голосов
/ 13 января 2019

Это окончательная версия (эти 4 строки заняли у меня весь день, лол):

in computed:
    appNotes(){
        let reverse=this.notes.slice().reverse()
        return this.check? reverse:this.notes
    }

Я удалил все остальное. Оказывается, все было просто.

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