【问题标题】:vue.js - problem with getting and displaying required value from object - onclickvue.js - 从对象获取和显示所需值的问题 - onclick
【发布时间】:2020-08-02 17:44:50
【问题描述】:

我用 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 项目中实现该目标,请提供帮助。 谢谢。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    在创建 bookData 对象时,有一个属性来显示按钮 (showButton),并且单击它会使其变为 false。参考下面的代码。

    工作示例是here

    this.bookData.push(      
    {
       avalable: true, 
       title,
       id,
       description,
       showButton = true
    }
    

    并在基于该模板的模板中显示书籍的按钮或标题。此处无需使用 ref 元素。

    <section  v-for="(bookTitle, index) in books"
       v-bind:key="index"
       >
       <button
          @click="bookTitle.showButton = !bookTitle.showButton"
          class="list-group-item"
          v-if="bookTitle.showButton"
          >{{bookTitle.title}}
       </button>
       
      <!-- Have the logic for title here -->
      <h2 v-if="!bookTitle.showButton">{{bookTitle.description}}</h2>
    </section>
    

    【讨论】:

    • 谢谢,@Sowmyadhar Gourishetty,但是我们如何才能显示特定的 bookData.description,它绑定到同一个 bookTitle.title?这必须通过 onclick 事件来完成。实际上,这就是问题所在。
    • 更新了代码和实例。如果您还需要什么,请告诉我
    • 这很好用,伙计@Sowmyadhar Gourishetty。非常感谢你。是否可以轻松制作某种切换开关来隐藏那些以这种方式显示的 bookData.description 元素?
    • @Milosh,给你jsfiddle.net/yLnhq89x。我已经直接创建了切换,您可以包含引导程序并从那里使用切换。
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2021-03-11
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多