vue中$ref的基本用法

1、使用在一般的标签上

<div id="app">
  <input ref="count" type="text" v-model="active.name" required name="name" value="">
</div>

这样在vue中我们可以使用$ref来获取dom节点,进行一些dom的操作

下面示例:控制input输入框的文字个数

new Vue({
    el:'#app',
    data:{
        active:{'name':''}
    },
    watch:{
        active:{
           handler:function(){
                var _this = this;
                var _sum = 4; //字数限制为4个
                _this.$refs.count.setAttribute("maxlength",_sum);
           },
           deep:true
        }
    },
})

2、使用在子组件上,可以用来获取子组件的属性值,假设子组件里面都有一个属性news

<div id="app">
    <hdnews ref="hdnews"></hdnews>
    <hdinfo ref="hdinfo"></hdinfo>
</div>
new Vue({
    el:'#app',
    mounted:function () {
        console.log(this.$refs.hdnews.news);
        console.log(this.$refs.hdinfo.news);
    }
})

猜你喜欢

转载自www.cnblogs.com/xiaoqi2018/p/10508835.html