【问题标题】:Rendering in vue for loop from object在 vue for 循环中从对象渲染
【发布时间】:2019-05-17 19:49:52
【问题描述】:

我想呈现问题和答案,并将一种样式附加到问题中,将另一种样式附加到答案中。

我的数据看起来像这样

 dialogTut:{
        mainTab:{
          q:"data with 42 people?",
          a:"hehe",
          q:"Are awesome people?",
          a:"sometimes",
          q:"Are awesome people2?",
        }

      },

我想在 Label 中渲染它,因为它的 nativescript (也许还有其他方法)

<StackLayout class="dialog">

        <Label v-bind:key="item.index"
              :text="item" 
              :class="[item==q ? 'h3' : '' , 'a']" 
              v-for="item in mainTab">
        </Label>

        <Button class="drawer-close-button" text="Cancel" @tap="closeDialog"></Button>
    </StackLayout>

我尝试了一些可能性 :class 但不起作用。 如何呈现整个列表并将 'h3' 类附加到 item.q 和 'answer' 类到 item.a ?

【问题讨论】:

    标签: javascript vue.js nativescript


    【解决方案1】:
    1. 如果 JS 对象中有重复的键,则只选择最后一个。你需要一个数组来存储它们。

    2. 可以使用对象语法绑定不同的类名:https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax

    -

    dialogTut: {
      mainTab: [
        { type: "q", index: 1, content: "data with 42 people?" },
        { type: "a", index: 2, content: "hehe" },
        { type: "q", index: 3, content: "Are awesome people?" },
        { type: "a", index: 4, content: "sometimes" },
        { type: "q", index: 5, content: "Are awesome people2?" }
      ]
    }
    
    <StackLayout class="dialog">
      <Label :key="item.index"
             :text="item.content"
             :class="{'h3': item.type == 'q', 'answer': item.type == 'a'}"
             v-for="item in mainTab">
      </Label>
      <Button class="drawer-close-button" text="Cancel" @tap="closeDialog"></Button>
    </StackLayout>
    

    【讨论】:

      【解决方案2】:

      替换为 :class="[item==q ? 'h3' : 'answer']" 或 :class="{ 'h3': item==q, 'answer': item==a }"

      【讨论】:

        【解决方案3】:

        我会以这种方式重组您的数据:

        mainTab:[
           {q:"data with 42 people?", a:"hehe"},
           {q:"Are awesome people?", a:"sometimes"}
        ]
        

        和你的 html:

        <template 
           :value="item.q" 
           v-for="(item,index) in mainTab">
           <p class="questionClass" :key="'q_'+index">{{item.q}}</p>
           <p class="answerClass" :key="'a_'+index">{{item.a}}</p>
        </template>
        

        【讨论】:

          猜你喜欢
          • 2021-05-15
          • 1970-01-01
          • 2017-12-30
          • 2018-01-16
          • 1970-01-01
          • 2020-05-19
          • 1970-01-01
          • 2016-04-10
          • 2019-04-23
          相关资源
          最近更新 更多