【Ant Design of Vue】v-ant-ref的使用,另一种获取组件实例的方法

一、介绍

  • v-ant-ref
    • 前提:需要在 ant-design 中使用
    • 表示将当前组件实例映射进 data 里面的某个值中,方便后期调用
  • ref
    • ref 放在普通的元素上,用 this.$refs 获取到的是 DOM 元素
    • ref 放在子组件上,用 this.$refs 获取到的是组件实例

二、v-ant-ref

<template>
  <div>
    <!-- 其中c指的是当前组件实例 -->
    <a-input v-ant-ref="(c) => (antInput = c)" placeholder="v-ant-ref" />
    <a-button v-ant-ref="(b) => (antButton = b)" type="primary" @click="onClick">v-ant-ref输入框获取焦点</a-button>
  </div>
</template>

<script>
export default {
    
    
  name: "testAntRef",
  data() {
    
    
    return {
    
    
      antInput: null,
      antButton: null,
    };
  },
  methods: {
    
    
    onClick() {
    
    
      console.log(this.antInput);
      console.log(this.antButton);
      this.antInput.focus();  // 聚焦输入框
    },
  },
};
</script>

<style lang="less" scoped>
.ant-input {
    
    
  width: 200px;
  margin: 10px;
}
</style>

在这里插入图片描述

三、ref

<template>
  <div>
    <a-input ref="input" placeholder="普通ref" />
    <a-button type="primary" @click="onClick">普通ref输入框获取焦点</a-button>
  </div>
</template>

<script>
export default {
    
    
  name: "testAntRef",
  data() {
    
    
    return {
    
    

    };
  },
  methods: {
    
    
    onClick() {
    
    
      this.$refs.input.focus();
    },
  },
};
</script>

<style lang="less" scoped>
.ant-input {
    
    
  width: 200px;
  margin: 10px;
}
</style>

PS:

  • v-ant-refref 两种写法效果是一致的

请添加图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43417844/article/details/130885842