vue ref 操作

ref 的妙用

1、引用 dom 元素

<h1 ref="myh1">引用 dom 元素</h1>
​
<script>
    methods:{
        show(){
            this.$refs.myh1.stylt.color="red"   //获取 dom 元素,使用 ref
        }
    }
</script>

 

2、引用组件

点击父组件的按钮,调用子组件的实例

子组件中:
<left ref="comleft"></left> //引用的子组件
 resetCount(){
    方法。。。
}
​
​
父组件中:
方法名(){
    this.$refs.comleft.resetCount();
    or
    this.$refs.count  += 1
}

 

3、文本框自动获得焦点

<input ref="iptRef"/>
​
方法名(){
    this.$refs.iptRef.focus()   //文本框获取焦点
}
​
//这个时候是会报错的!

遇见报错:iptRef -> undefined ,因为这个事件应该发生在 页面渲染之后。

 

this.$nextTick(cb)方法 //下次点击的时候调用
this.$nextTick(() => {
    this.$refs.iptRef.focus()
})
​
是在生命周期中的 methods 中,不要放在 update 中
 
posted @ 2022-07-07 23:00  东八区  阅读(172)  评论(0)    收藏  举报