1

我是 Vuejs 的新手。这是我需要做的。

<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>

我想要做的不是用 id x 定义 div 两次,因为它很大。

4

1 回答 1

2

使您的“div”成为一个组件并在两个地方引用它。

有很多方法可以定义你的组件。此示例仅显示一个。如果您使用的是 WebPack,请使用单个文件组件。然后,您可以将脚本、html 和 css 全部放在一个预编译的文件中。这是管理“巨大”div 的最佳方式。然后您可以继续重构并将其分解为更多组件。

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>

于 2018-08-07T12:42:47.800 回答