-1

I'm trying to build a quick prototype of a simple interactive story with Vue.js (example of what I'm trying to achieve : https://www.getbadnews.com/#play) but I can't get my Vue app to display elements from an array one by one in a list inside an unordered list when I click a button.

Any idea as to the best way to achieve this?

Here is my current code:

const InteractiveStory = {
  data() {
    return {
      list: [];
    }
    
  },
  methods: {
    addList: function() {
      var number = 0;
      var storySnippets = ["Hello", "Two", "Three", "Four"];
      this.list.push(storySnippets[number]);
      number++;
    },
  },
}

Vue.createApp(InteractiveStory).mount('#story')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="story">
  <ul>
    <li v-for="item in list"></li>
  </ul>
  <button @click="addList()">Next</button>
 </div>

Thanks for your help, I've been stuck on this for two days :)

Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

1

I'd actually approach this in a different way... start with the full list and use a computed property to progressively reveal elements.

const InteractiveStory = {
  data: () => ({
    sourceList: ["Hello", "Two", "Three", "Four"],
    index: 0
  }),
  computed: {
    list: ({ sourceList, index }) => sourceList.slice(0, index)
  },
  methods: {
    addList() {
      this.index = Math.min(this.index + 1, this.sourceList.length)
    }
  }
}

Vue.createApp(InteractiveStory).mount('#story')
<script src="https://unpkg.com/vue@next"></script>

<div id="story">
  <ul>
    <li v-for="item in list">{{ item }}</li>
  </ul>
  <button @click="addList">Next</button>
</div>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thank you it works! However since I've started learning Vue directly on V3, I am somewhat unfamiliar with this sequence: list: ({ sourceList, index }) => sourceList.slice(0, index) any idea how I should rewrite this part with Vue 3 syntax? – Charlie Maréchal Dec 16 '20 at 03:57
  • @CharlieMaréchal that works just fine in Vue 3 (I updated my answer from Vue 2 to 3) – Phil Dec 16 '20 at 03:59