vue的ref属性

 ref 被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的$refs对象上,如果在普通的DOM元素上使用,引用指向的就是DOM元素,如果用在子组件上,引用就指向组件实例。

<!-- vm.$refs.p will be the DOM node -->
<p ref="p">hello</p>

<!-- vm.$refs.child will be the child comp istance -->
<child-comp ref="child"></child-comp>

 

 因为 ref 本身是作为渲染结果被创建的,只能初始化渲染完成后才能访问它们。

 

 vue的ref属性 完成数据绑定

<div id="app">
  <h1>{{ message }}</h1>
  <button ref="myButton" @click="clickedButton">点击偶</button>
</div>
let app = new Vue({
    el: '#app',
    data () {
        return {
            message: 'Hi!大漠'
        }
    },
    methods: {
        clickedButton: function () {
            console.log(this.$refs)
            this.$refs.myButton.innerText = this.message
        }
    }
})

 

vue的ref属性获取/设置标签的样式

<div >
    <div ref="image" class="image"></div>
    <div ref="content" class="content"></div>
</div>
 
<style>
    .image{
        width:100%;
        height:0;
        padding-top:70%;
    }
    .content{
        position:absolute;  
        width:100%;
        top:0;
        left:0;
        right:0;
        bottom:0;  
    }
    
</style>
 
<script>
    export default{
        mounted(){
            setTimeout(()=>{
                this.$refs.content.$el.style.top=`${this.$refs.image.clientHeight}px`
            },20)
        }
    }
 
</script>

 

posted on 2021-01-28 14:04  zhishiyv  阅读(255)  评论(0编辑  收藏  举报

导航