Categories
Vue Answers

How to Output a Comma-Separated Array with Vue.js?

Spread the love

Sometimes, we want to output a comma-separated array with Vue.js.

In this article, we’ll look at how to output a comma-separated array with Vue.js.

Output a Comma-Separated Array with Vue.js

To output a comma-separated array with Vue.js, we can use the v-for directive.

For instance, we can write:

<template>
  <div id="app">
    <span v-for="(list, index) in lists" :key="list">
      <span>{{ list }}</span>
      <span v-if="index + 1 < lists.length">, </span>
    </span>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      lists: ["Vue", "Angular", "React"],
    };
  },
};
</script>

We use the v-for directive to render the list array into a comma-separated list.

We add a comma only when index + 1 < lists.length so we only add the commas between the words.

A shorter way to render the words in the array into a comma-separated list is to use the array join method.

For example, we can write:

<template>
  <div id="app">
    <span>{{ lists.join(", ") }}</span>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      lists: ["Vue", "Angular", "React"],
    };
  },
};
</script>

to combine the words with the join method in the template.

Either way, we get:

Vue, Angular, React

rendered on the screen.

Conclusion

To output a comma-separated array with Vue.js, we can use the v-for directive.

A shorter way to render the words in the array into a comma-separated list is to use the array join method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *