2

I have a static array data like this

const names = ["Amy", "Joseph", "Hank"];

I want to loop them in my markup, in React, I can simply do this:

import React, { memo } from "react";

// these guys are static values!
const names = ["Amy", "Joseph", "Hank"];

const App = () => (
  <div>
    {names.map(name => ( // render once and no more!
      <span key={name}>{name}</span>
    ))}
  </div>
);

export default memo(App); // won't re-render anymore!

But in Vue, the only way I can think of is doing this:

<template>
  <div>
    <span v-for="name in names" :key="name">{{ name }}</span>
  </div>
</template>

<script>
const names = ["Amy", "Joseph", "Hank"];

export default {
  data() {
    return {
      names // I have to put these guys in data property, now it becomes reactive, I don't want this. Although this will only render once.
    };
  }
};
</script>

I have to put my names in data() or computed properties, but this will cause them to be reactive, is there any other way to do this?

4
  • Why do you want to do that? Commented Jan 24, 2020 at 16:09
  • @ZohaibIjaz because this will cause names to have getters and setters, which makes javascript doing none necessary things. Commented Jan 24, 2020 at 16:10
  • 2
    I think this is a duplicate. stackoverflow.com/a/45815401/9236687 Commented Jan 24, 2020 at 16:13
  • 1
    This post might also help. Commented Jan 24, 2020 at 16:35

1 Answer 1

2

You can create a custom option like so

export default {
  data() {
    return {
      //your reactive thins here
    };
  }
  names : ["Amy", "Joseph", "Hank"],
  .......
};

And finally in your template you can iterate over it like

<template>
  <div>
    <span v-for="name in $option.names">{{ name }}</span>
  </div>
</template>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.