【问题标题】:How to display elements from an array one by one by pushing a button with Vue.js 3如何通过使用 Vue.js 3 按下按钮来一一显示数组中的元素
【发布时间】:2021-03-26 15:23:33
【问题描述】:

我正在尝试使用 Vue.js 构建一个简单交互式故事的快速原型(我想要实现的示例:https://www.getbadnews.com/#play),但我无法让我的 Vue 应用程序显示来自当我单击按钮时,在无序列表内的列表中逐一排列。

您知道实现这一目标的最佳方法吗?

这是我当前的代码:

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>

感谢您的帮助,我已经坚持了两天:)

【问题讨论】:

  • list: []; 不应以分号结尾。您使用的是 Vue 2 还是 Vue 3?您的 sn-p 包括 v2,但 Vue.createApp 是 v3 的东西
  • 对不起,忘了说我使用的是 Vue.js 3 !

标签: javascript html vue.js vuejs3


【解决方案1】:

我实际上会以不同的方式处理此问题...从完整列表开始,并使用计算属性逐步显示元素。

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>

【讨论】:

  • 谢谢它的工作!然而,由于我已经开始直接在 V3 上学习 Vue,所以我对这个序列有点不熟悉: list: ({ sourceList, index }) => sourceList.slice(0, index) 知道我应该如何用 Vue 3 重写这部分语法?
  • @CharlieMaréchal 在 Vue 3 中运行良好(我将答案从 Vue 2 更新到 3)
猜你喜欢
  • 1970-01-01
  • 2022-11-02
  • 2021-10-18
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多