Search code examples
javascriptvue.jsnativescript

Rendering in vue for loop from object


I want to render question and answers and append one style to questions and other style to answers.

My data would look like this

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

      },

And I want to render this in Label cause its nativescript (maybe is there other method )

<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>

I tried some possibilities :class but do not work. How to render this whole list and append 'h3' class to item.q and 'answer' class to item.a ?


Solution

    1. If there are duplicated keys in a JS object, only the last one is picked. You need an array to store them.

    2. You can use object syntax to bind different class names: https://v2.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>