source

콤마 구분 배열 출력 방법

goodcode 2022. 7. 26. 23:38
반응형

콤마 구분 배열 출력 방법

VueJ에서는 어레이를 루프할 수 있습니다.

<span v-for="(element, index) in list">{{ element }}</span>

쉼표로 구분된 목록을 원하는 경우 어떻게 해야 합니까?를 들어, 「」의 ,list = ["alice", "bob", "chuck"]위의 출력은 다음과 같습니다.

<span>alice</span><span>bob</span><span>chuck</span>

하지만 내가 원하는 건

<span>alice</span>, <span>bob</span>, <span>chuck</span>

이게 가능합니까?

콤마 구분만 신경쓰는 경우 Javascript의 내장 Join 메서드를 사용합니다.

{{ list.join(', ') }}

조건부 렌더링을 사용하여 마지막으로 숨길 수 있습니다.,

var demo = new Vue({
  el: '#demo',
  data: function() {
    return {
      lists: ['Vue', 'Angular', 'React']
    };
  }
})
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="demo">
  <span v-for="(list, index) in lists">
    <span>{{list}}</span><span v-if="index+1 < lists.length">, </span>
  </span>
</div>

하면 .v-if첫 번째 인수 위에 조건이 있는 Atribute를 지정합니다.사용을 회피합니다.

var app = new Vue({
  el: '#app',
  data: {
    list: ['john', 'fred', 'harry']
  }
})
<script src="https://vuejs.org/js/vue.min.js"></script><div id="app">
  <span v-for="(element, index) in list">
    <span v-if="index != 0">, </span><span>{{ element }}</span>
  </span>
</div>

대신 제가 하게 된 것은 다음과 같습니다.

<span v-for="element in list" class="item">
  <span>{{ element }}</span>
</span>

그리고 CSS에서는:

.item + .item:before {
  content: ", ";
}

JS를 사용하는 .Array.join

<span>{{ list.join(', ') }}</span>

'템플릿'을 사용한 솔루션

 <template v-for="(element, index) in list">
   <span>{{element}}</span><template v-if="index + 1 < list.length">, </template>
 </template>

JS 방식으로 수행하려는 경우 계산된 속성만 수행할 수 있습니다. 또한 스팬 방법을 계속할 수도 있습니다.

computed {
  listCommaSeparated () { return this.list.join(', '); },
  listCommaSpans () { return '<span>' + this.list.join('</span><span>') + '</span>'; },
},

렌더링 성능의 관점에서 이 방법이 선호되는 것은 확실합니다.

제가 선호하는 다른 대안을 추가해 보겠습니다.

<span v-for="(item, index) in list">
    {{ item }}{{ (index+1 < list.length) ? ', ' : '' }}
</span>

내 컴포넌트:

<template>
<ul v-if="model.length">
    <li v-for="item in model">{{item}}</li>
</ul>
</template>
<style scoped>
ul {
    list-style: none;
}
li {
    display: inline-block;
}
li:not(:last-child)::after {
    content: ", ";
}
</style>
<script>
export default {
    props: ['model']
};
</script>

한 입니다.
<span v-for="(item,i) in items"> {{(item !='' && i !=0) ? ',' : ''}} {{item.title}} </span>

돔 모양을 제어하고 싶은 경우(예를 들어 실제로 문의한 돔 구조를 실현하고 싶은 경우) 다음과 같은 기능 구성요소를 작성할 수 있습니다.

<script>
// RenderList.vue
export default {
  functional: true,
  render(createElement, context) {
    // Read the list of entries by accessing the prop "list"
    const listEntries = context.props.list;

    // Return a custom list of elements for each list entry.
    // Only return a `,` if it's not the last entry.
    return listEntries.map((listElement, idx) => {
      return [
        createElement("span", listElement),
        idx < listEntries.length - 1 ? ", " : "",
      ];
    });
  },
};
</script>

이 컴포넌트는 다음과 같이 사용합니다.

<template>
  <RenderList :list="['alice', 'bob', 'chuck']" />
</template>

수표로 i > 0을 사용하는 것을 제안해도 될까요?

{{ ' }}}은(는) 공간을 확보하여 스팬이 비어 있지 않도록 세퍼레이터를 포장하였습니다.

<span
    v-for="(item, i) in list"
    :key="i">
   <span v-if="i>0">{{ ', ' }}</span>
   <span class="text-nowrap">{{ item }}</span>
</span>

또는

<span
    v-for="(item, i) in list"
    :key="i">
   <!-- if not wrapped in a span will leave a space before the comma -->
   <span>{{ (i > 0 ? ', ' : '') }}</span>
   <span class="text-nowrap">{{ item }}</span>
</span>

를 사용하는 경우는, 다양한 뷰가 있습니다.:after ★★★★★★★★★★★★★★★★★」:before브라우저가 윈도 크기를 조정할 때 콤마를 문자열로 처리하지 않는 것은 좋은 생각이 아닙니다.

각 반복에서 조건부 연산자를 사용하여 첫 번째 요소인지 마지막 요소인지 확인하려고 하면 항목이 많을 경우 오버헤드가 발생합니다.또한 변경사항이 검출될 때마다 조건을 재평가합니다.

두하려면 쉼표를 CSS를 수 .:last-child

<template v-for="item in list">
    <span class="item">
        {{item}}
        <span class="comma">
            ,
        </span>
    </span>
</template>

및 CSS에서

.item:last-child .comma {
    display: none;
}

언급URL : https://stackoverflow.com/questions/42129534/vuejs-how-to-output-a-comma-separated-array

반응형