0
点赞
收藏
分享

微信扫一扫

《Vue学习》ref

生态人 2022-03-11 阅读 87

ref放在系统的标签,如butoon,h1这种,可以获得dom元素,放在自定义的组件上则获得的是Vc。

利用Ref获得 

<template>
    <div>
        <h1 v-text="msg" ref="title"></h1>
        <button @click="showDom" ref="btn">点我输出上方的Dom元素</button>
        <School ref="sch"/>
    </div>
</template>

<script>
    import School from './components/School.vue'
    export default {
        name:'App',
        components:{School},
        data(){
            return {
                msg:'欢迎学习Vue'
            }
        },
        methods:{
            showDom(){
                console.log(this.$refs.title),//获得是真实Dom
                console.log(this.$refs.btn),//获得是真实Dom
                console.log(this.$refs.sch)//获得的是组件的实例对象Vc
            }
        }
    }
</script>

 利用id获得

<template>
    <div>
        <h1 v-text="msg" id="title"></h1>
        <button @click="showDom" id="btn">点我输出上方的Dom元素</button>
        <School id="sch"/>
    </div>
</template>

<script>
    import School from './components/School.vue'
    export default {
        name:'App',
        components:{School},
        data(){
            return {
                msg:'欢迎学习Vue'
            }
        },
        methods:{
            showDom(){
                // console.log(this.$refs.title),//获得是真实Dom
                // console.log(this.$refs.btn),//获得是真实Dom
                // console.log(this.$refs.sch)//获得的是组件的实例对象Vc
                console.log(document.getElementById('title')),
                console.log(document.getElementById('btn')),
                console.log(document.getElementById('sch'))
            }
        }
    }
</script>

 可以看出,用id获得的都是真实Dom,而用ref对于自定义组件获得的是实例对象,这对以后的组件通信很有帮助。

举报

相关推荐

vue中ref属性

Vue 中的 Ref

vue3.0使用$ref

vue的ref和refs

vue3 #ref #reactive

vue 中的 ref 简单总结

0 条评论