vue 之 ref 的使用

197 阅读1分钟

用法一:基础用法,可以通过给某个元素设置 ref 属性来获取到该元素的 DOM ,进而可以获取到该元素的各种属性

例如:

给元素设置 ref 属性,ref 的值可以自定义(这里值为 input )

<input ref="input" type="text" value="test" />

然后再 mounted 钩子函数里面或者在 methods 属性里面使用 this.$refs.input 就可以获取到 input 这个元素

注意:ref 获取元素必须在渲染之后也就是 mounted 后获取,因为获取的 dom 元素,dom 需要渲染出来后才能获取,在 created 里面是获取不到的

mounted: function () {
    this.$nextTick(function () {
        console.log(this.$refs.input);
        console.log(this.$refs.input.value);
    });
}
methods: {
    getValue: function () {
        console.log(this.$refs.input);
        console.log(this.$refs.input.value);
    }
}

用法二:使用 ref 获取子组件的 data 值或者调用子组件的方法

在子组件中有 message 值和一个 fn 方法

data: function () {
    return {
        message: '123'
    };
}
methods: {
    fn: function () {
        console.log('子组件的方法被调用');
    }
}

给子组件上设置 ref 属性值为 child

<child-component ref="child"></child-component>

ref 绑在元素上可以获取元素,那么绑定给子组件就可以获取整个子组件,进而可以获取到子组件里面的 data 值或者调用子组件的方法

  1. 获取子组件的data里面msg的值
console.log(this.$refs.child);
console.log(this.$refs.child.message);
  1. 在父组件中使用 ref 调用子组件的方法
console.log(this.$refs.child.fn());

ref 不仅可以获取本页面的 dom 元素,还可以获取子组件,ref 设置给页面元素就能获取这个页面元素,设置给组件,就能获取到这个组件。

github demo:http://github.crmeb.net/u/lei

gitee demo:https://gitee.com/ZhongBangKeJi/crmeb_zzff_class

demo 中详细的应用示例,可供参考。