有没有办法从其模板中访问 Vue 组件的索引——或其他一些唯一标识符?

Is there a way to access a Vue Component's index — or some other unique identifier — from within its template?

如果我正在创建(可能是动态的)n 个组件,其中每个组件都需要从其自己的模板中引用唯一的 index/id/reference 是否存在这样的事物?我没有使用 for in 循环来生成组件,所以我认为我无法访问(阅读:已经尝试使用……)$index.

我拼凑了一个(糟糕的)我正在尝试做的非常糟糕的说明,但我怀疑有一个预建的方法。

https://jsfiddle.net/itopizarro/dw070yyL/

好吧,在我阅读关于您不想使用的部分之前,我做了一个完整的示例 $index 如果有帮助的话,这里是示例:https://jsfiddle.net/dw070yyL/1/

但您可以使用 v-ref 为子组件提供唯一标识符,请参阅 http://vuejs.org/api/#v-ref

<bar v-ref:bar-one></bar>

然后在父组件中你可以使用this.$refs.barOne来引用那个子组件。

这也适用于列表,如文档中所示:

<bar v-ref:bar-list v-for="item in list"></bar>

将使this.$refs.barList成为一个子组件数组

我还要说你这样做的方式还不错,例如 this Wizard component 通过在 ready() 中迭代 this.$children 使用类似的方法函数并相应地设置它们的每个索引:

  ready() {
    this.countItems = this.$children.length

    this.$children.forEach((item, index) => {
      item.index = index
    })
  }

您可以使用方法在模板中分配索引,而无需使用就绪函数。

Vue.component('task', {
  methods: {
    onStartGetIndex() {
      this.$index = this.$root.$children.length;
      return this.$index;
    }
  },
  template: '<li>{{ onStartGetIndex() }}</li>'
});

或者将索引保存在属性中,以便在模板中更多地引用。

Vue.component('task', {
  methods: {
    onStartGetIndex() {
      this.$index = this.$root.$children.length;
      return this.$index;
    }
  },
  template: '<li :index="onStartGetIndex()">{{ this.$index }}</li>'
});

以上两个仅在进行更改然后组件刷新之前有效。

您可以添加一个查找索引的方法,如果找不到则使用长度。

  Vue.component('task', {
    methods: {
      getIndex() {
        if (this.$root.$children.indexOf(this) == -1) {
          this.$index = this.$root.$children.length;
        } else {
          return this.$root.$children.indexOf(this);
        }
      },
    },
    template: '<li>{{ getIndex() }}</li>'
  });