Vue 中必不可少的——ref 和 $refs 获取组件


ref 以标签属性的形式存在来接收String,被用来给元素子组件注册引用信息

$refs 以对象的方式存在,表示持有ref属性的所有组件

本篇文章是利用ref和$refs可以用于获取组件实例

首先在子组件内用v-model绑定输入框的值(type值暂时都设置为text)

在子组件用methods设置

getForm()收集表单数据 和 resetForm()重置表单数据

然后在父组件里面给两个button注册点击事件

@click="handelGet" 和 @click="handelReset"

在父组件用methods设置

handelGet()  和   handelReset()

可以在父组件用 console.log(this.$refs.baseForm)检查一下

可以看到getForm() 和 resetForm()

此时就可以在父组件直接调用

console.log(this.$refs.baseForm.getForm());

这里还没有写任何值,所以是空的

写上账号和密码之后就可以在控制台获取到了

此时可以将密码框的type改回 password(效果其实是一样的)

最后重置数据就是让账号密码框都为空,直接调用一下handelReset()方法就可以

this.$refs.baseForm.resetForm()

ok,这样就完成了ref 和 $refs 获取组件

下面是完整代码,可以参考一下

父组件App.vue

<template>
  <div class="app">
    <BaseForm ref="baseForm"></BaseForm>
    <button @click="handelGet">获取数据</button>
    <button @click="handelReset">重置数据</button>
  </div>
</template>

<script>
import BaseForm from './components/BaseForm.vue'
export default {
  components: {
    BaseForm,
  },
  methods: {
    handelGet(){
      console.log(this.$refs.baseForm.getForm());
    },
    handelReset(){
      this.$refs.baseForm.resetForm();
    }
  }
}
</script>

<style scoped>
  button{
    margin: 5px 10px;
  }
</style>

子组件BaseForm.vue

<template>
  <div class="app">
    <div>
      账号: <input v-model="username" type="text">
    </div>
     <div>
      密码: <input v-model="password" type="password">
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
    }
  },
  methods: {
    // 1.收集表单数据,返回一个对象
    getForm() {
      return{
        // console.log('获取表单数据', this.username, this.password),
        username:this.username,
        password:this.password  
      }
    },
    // 2.重置表单
    resetForm() {
      this.username = ''
      this.password = ''
      console.log('重置表单数据成功');
    },
  }
}
</script>

<style lang="less" scoped>
.app {
  width: 300px;
  height: 100px;
  border: 2px solid #000000;
  padding: 15px;
  border-radius: 10px;
  div{
    margin: 15px 0;
  }
}

</style>

  • 15
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值