vue 动态绑定ref 父组件获取自组件data数据

 vue中用ref 可以引用元素或组件中的数据,静态绑定用法非常简单,例如:this.$refs["xxx"].func() 或this.$refs["xxx"].msg   父组件调用子组件中的方法或数据。 

如果在父组件中用v-for循环渲染子组件,并且需要在父组件获取所有子组件中的数据,那么就需要动态绑定ref,代码如下

<template>
  <Base>
    <div>
      <div v-for="item in itemList" :key="item.id">
        <child :ref="`child${item.id}`"></child>
      </div>
    </div>
    <el-button @click="onBtn">结果</el-button>
  </Base>
</template>

<script>
import child from "./child.vue";
export default {
  components: {
    child,
  },
  data() {
    return {
      itemList: [
        {
          id: 0,
        },
        {
          id: 1,
        },
        {
          id: 2,
        },
      ],
    };
  },
  methods: {
    onBtn(){
      this.itemList.forEach(item => {
        console.log('item is: ', this.$refs[`child${item.id}`][0].msg)
      })
    }
  },
};
</script>

<style lang="scss" scoped>
</style>

:注意父组件在取得子组件数据写法如下:this.$refs[`child${item.id}`][0].msg  

猜你喜欢

转载自blog.csdn.net/liubangbo/article/details/132721381
今日推荐