AbbasFaisal
AbbasFaisal

Reputation: 1490

vuejs render part of template inside different elements without repeating

I am new to Vuejs. This is what I need to do.

<div v-for="r in records">
    <div v-if="r.something">
        <div id="x">
            {{ r. something}}
            more of r here.
        </div>
    </div>

    <div v-else id="x">
        same div as in the block above.
    </div>
</div>

What I want do is not define div with id x two times as it is huge.

Upvotes: 1

Views: 328

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29109

Make your 'div' a component and refer to it in both places.

There are many ways to define your component. This is example shows just one. If you are using WebPack, use a single file component. You can then have your script, html, and css all in one file that gets precompiled. That's the best way to manage your 'huge' div. Then you can continue to refactor and break it up into more components.

const myComponent = {
  template: "<div :id='id'>HELLO, my id is {{id}}. r.foo is {{r.foo}} </div>",
  props: {
    id: String
  },
  data() {
    return {
      r: {
        foo: 'bar'
      }
    }
  }
}
<div v-for="r in records">
  <div v-if="r.something">
    <my-component id='x' />
  </div>

  <div v-else id="x">
    <my-component id='x' />
  </div>
</div>

Upvotes: 2

Related Questions