简体   繁体   中英

Vuejs - how to get nested elements

I am trying to convert this to vuejs. I faced some difficulties.

1st. How can I access nested sub elements?

<div ref="tickerwrapper" class="tickerwrapper">
  <ul ref="list" class='list'>
    <li ref="listitem" class='listitem'>
      <span>This is list item 1</span>
    </li>
    <li ref="listitem" class='listitem'>
      <span>This is list item 2</span>
    </li>
    <li ref="listitem" class='listitem'>
      <span>This is list item 3</span>
    </li>
    <li ref="listitem" class='listitem'>
      <span>This is list item 4</span>
    </li>
    <li ref="listitem" class='listitem'>
      <span>This is list item 5</span>
    </li>
  </ul>
</div>
const tickerWrapper = this.$refs.tickerwrapper

How can I access the list and listitem s using tickerWrapper? I wanna get a list and a listitem[]

2nd.

var $clonedList = $list.clone();

How can I vue implement the corresponding clone()? Somebody help me.

I put together an example of how to get references to child components and their DOM elements. I wrapped the <li> tag in a child component.

TicketWrapper.vue

<template>
  <div class="ticket-wrapper">
    <h3>Ticket Wrapper</h3>
    <div class="row">
      <div class="col-md-4">
        <ul>
          <list-item v-for="(item, index) in items" :key="index" :itemText="item.text" ref="listItems"/>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import ListItem from './ListItem.vue'

  export default {
    components: {
      ListItem
    },
    data() {
      return {
        items: [
          {
            text: 'item1'
          },
          {
            text: 'item2'
          },
          {
            text: 'item3'
          },
        ]
      }
    },
    mounted() {
      console.log(this.$refs.listItems)
      this.$refs.listItems.forEach( listItemComponent => {
        console.log(listItemComponent.$el.innerText);
      })
    }
  }
</script>

ListItem.vue

<template>
  <li class="list-item">{{ itemText }}</li>
</template>

<script>
  export default {
    props: {
      itemText: {
        type: String,
        required: true
      }
    }
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM