vue3 ref调用v-for遍历的子组件

链接: link

ref调用v-for遍历的子组件

父组件

<template>
  <div>
	<Children
      v-for="(item, index) in list"
      :key="item.id"
      :itemData="item"
      :index="index + 1"
      :ref="(el: any) => { creatRef(el, index)}"
      @update="update"
    />
    <button onclick="submit"></button>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import Children from './Children.vue';
const listRefs = ref<any>([]),
      list = ref([
      	{id: 1, name: '11'},
      	{id: 2, name: '22'},
      ]);
// 遍历生成多个ref
const creatRef = (el: any, index: number) => {
  if (el) {
    listRefs.value[index] = el;
  }
};
const update = (val: any) => {
	console.log(val);
}
const submit= () => {
	listRefs.value?.forEach((item: any) => {
	  item.todo();
	});
}
onMounted(() => {})
</script>

子组件Children

<template>
  <div>
  	<input v-model="itemData.name" />
  </div>
</template>
<script lang="ts" setup>
import {reactive, watch} from 'vue';
const emit = defineEmits(['update']);
const props = defineProps({
  itemData: {
    type: Object,
    default: () => {},
  },
  index: {
    type: number,
    default: 0,
  },
});
const todo = () => {
	console.log('todo');
	emit('update', {
      index: props.index,
      name: itemData.name,
    });
};
defineExpose({
  todo,
});
watch(
	() => props.itemData,
	(newVal) => {
	 	console.log('newVal=', newVal);
	},
	{ deep: true, immediate: true },
);
GitHub 加速计划 / vu / vue
108
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
9e887079 [skip ci] 1 年前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐