vuejs получает доступ к ref внутри компонентов v-for

Отрендерите некоторые компоненты из цикла v-for. Ссылки определяются следующим образом: :ref="'category_' + index" Вот как эти ссылки отображаются в консоли по адресу: console.log(this.$refs):

category_0: [VueComponent]
category_1: [VueComponent]
category_2: [VueComponent]
category_3: [VueComponent]
category_4: [VueComponent]
category_5: [VueComponent]
category_6: [VueComponent]
category_7: [VueComponent]
category_8: [VueComponent]
__proto__: Object

Если я пытаюсь получить доступ следующим образом: console.log(this.$refs.category_0), я получаю undefined. Любая другая определенная ссылка (не называемая «category_..») работает отлично.

Что здесь не так?

<el-form-item v-for="(category,index) in Object.Products" :key="index" 
  :label="category.Name">

    <Select-product v-model="category.IdSelected" :ref="'category'" 
      ProductCategory='Ingredient' @return="handleSelectIngredient"/> 

</el-form-item>


person victor vacarescu    schedule 21.03.2020    source источник
comment
Вам нужно показать, как и где вы делаете журналы консоли...   -  person Eggon    schedule 21.03.2020
comment
@Эггон async handleSelectModelAutomat(item) { var response = await this.post("info/get", {IdModel: item}) this.Object.Products = response.Result console.log(this.$refs) console.log(this.$refs.category_0) }   -  person victor vacarescu    schedule 21.03.2020
comment
Привет @victorvacarescu, не могли бы вы обновить вопрос, чтобы получить код, который вы используете в своем компоненте? Трудно сказать без хорошего взгляда на ваш код.   -  person Liam    schedule 21.03.2020


Ответы (2)


Вот была проблема (может быть, это поможет другим):

Вызов категории ref (console.log(this.$refs.category)) получил undefined, потому что компонент в то время был недоступен, он был отрендерен в DOM позже (вопросы миллисекунд). Итак, $nextTick() выполнила свою работу.

    async handleSelectModelAutomat(item) {
      var response         = await this.post("info/get", {IdModel: item}); 
      this.Object.Products = response.Result; 

      await this.$nextTick() 
      console.log(this.$refs.category_0) }
person victor vacarescu    schedule 22.03.2020

Когда вы назначаете ссылки на v-for, Vue извлекает все эти ссылки из массива. Так что нет необходимости в :ref="'category_' + index".

Вместо этого вы можете просто сделать ref="category" и получить доступ к ссылке вот так this.$refs.category[0].

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    arr: [1, 2, 3, 4, 5]
  },
  methods: {
    test() {
      console.log(this.$refs.category);
      console.log(this.$refs.category[0]);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="nbr in arr" ref="category">
    {{ nbr }}
  </div>
  <button @click="test">
    test
  </button>
</div>

Когда ref используется вместе с v-for, вы получаете ref в виде массива, содержащего дочерние компоненты, отражающие источник данных.

https://vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

person Pierre Said    schedule 21.03.2020
comment
Пробовали раньше, как вы сказали, но все равно получили: [Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property '0' of undefined". Думаю тут другая проблема... - person victor vacarescu; 21.03.2020