vue.js - 从对象获取和显示所需值的问题 - onclick

我一直在用 vue.js 方法、指令、各种循环和高阶函数尝试很多事情,并尝试了很多事情$this.refs…… 目标是在点击标题时显示一本书的描述(这是按钮元素 - vue .js 模板,它的渲染工作正常 - 正确显示):


<section  v-for="(bookTitle, index) in books"

      v-bind:key="index"

      

      >

    <button

      ref="el"

      @click="hidden = !hidden"

      class="list-group-item"

    v-if="bookTitle.title"

    >{{bookTitle.title}}

    </button></section>

我获取了一个 API,并根据其属性创建了一个数据数组:


mounted() {

fetch("https://www.googleapis.com/books/v1/volumes?q=%22coding%22", {

  method: "get",

})

  .then((res) => {

    return res.json();

  })

  .then((result) => {

    let title;

    let description;

    let authors;

    let id;

    for (var i = 0; i < result.items.length; i++) {

      title = result.items[i].volumeInfo.title;

      description = result.items[i].volumeInfo.description;

      authors = result.items[i].volumeInfo.authors;

      id = result.items[i].id;

      this.bookData.push(

      

        {

        avalable: true, 

        title,

        id

        },

        {

        authors,

        description,

        id

        }

也许,问题出在我对对象的表述上。如果有一些简单的方法可以在 vue.js 项目中实现该目标,请提供帮助。谢谢。


繁星淼淼
浏览 176回答 1
1回答

LEATH

在创建 bookData 对象时,有一个属性来显示按钮 (showButton),并且单击它会使它变为 false。参考下面的代码。工作示例在这里this.bookData.push(&nbsp; &nbsp; &nbsp;&nbsp;{&nbsp; &nbsp;avalable: true,&nbsp;&nbsp; &nbsp;title,&nbsp; &nbsp;id,&nbsp; &nbsp;description,&nbsp; &nbsp;showButton = true}并在基于此的模板中显示书的按钮或标题。这里不需要使用 ref 元素。<section&nbsp; v-for="(bookTitle, index) in books"&nbsp; &nbsp;v-bind:key="index"&nbsp; &nbsp;>&nbsp; &nbsp;<button&nbsp; &nbsp; &nbsp; @click="bookTitle.showButton = !bookTitle.showButton"&nbsp; &nbsp; &nbsp; class="list-group-item"&nbsp; &nbsp; &nbsp; v-if="bookTitle.showButton"&nbsp; &nbsp; &nbsp; >{{bookTitle.title}}&nbsp; &nbsp;</button>&nbsp; &nbsp;&nbsp; <!-- Have the logic for title here -->&nbsp; <h2 v-if="!bookTitle.showButton">{{bookTitle.description}}</h2></section>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript