[Ant Design of Vue] The use of v-ant-ref, another way to get component instances

1. Introduction

  • v-ant-ref
    • Prerequisite: need to ant-designbe used in
    • Indicates that the current component instance is mapped into dataa certain value inside, which is convenient for later calls
  • ref
    • refPut it on an ordinary element, and this.$refsget DOMthe element with
    • refPut it on the subcomponent, and this.$refsget the component instance with

Two, 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>

insert image description here

Three, 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-refrefThe effect of the two writing methods is consistent with

Please add a picture description

Guess you like

Origin blog.csdn.net/weixin_43417844/article/details/130885842