vue基础(6)、DOM元素相关

this.$ref获取DOM元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>

<body>
    <div id="a1">
        <app></app>
    </div>
</body>

<script>
    var subComp={
        template:'<div class="sub_com"><h1>hello Vue.Js</h1></div>',
        data:function () {
            return{
                msg:'hello!'
            }
        }
    };

    var App={
        template:'' +
        '<div>' +
        '   <subComp ref="sub_c"></subComp>' +
        '   <h1>app</h1>' +
        '   <button ref="btn">点击</button>' +
        '   <p ref="text">coding is funny!</p>' +
        '</div>',
        beforeCreate(){
        },
        created(){
            // console.log(this.$refs.btn.innerHTML)// undefined
            // 此时元素还未挂在到dom中
        },
        mounted(){
            console.log(this.$refs.sub_c)  // 取到的是组件对象
            console.log(this.$refs.sub_c.msg)  // 取到组件对象的data中的值
            // console.log(this.$refs.btn.innerHTML);
            // console.log(this.$refs.text.innerHTML)
        },
        components:{
            subComp:subComp,
        }
    };

    new Vue({
        el:'#a1',
        data:{
        },
        components:{
            app:App,
        }
    });
</script>
</html>

$属性总结

$parent

获取当前组件的父组件。

 mounted(){
            console.log(this.$parent.d1)
 }// 直接获取父组件中data中的值

$children

获取当前组件的子组件,是array格式。

# 示例见上,修改部分
mounted(){
    console.log(this.$children[0].msg)
}  // hello

$root

直接获取new Vue的实例化对象。

$el

获取组件对象的DOM元素


使用$nextTick的特殊情况

vue实现响应式并不是数据发生变化之后DOM立即发生变化,而是按一定的策略进行DOM更新。$nextTick是在下次DOM更新循环结束之后执行的延迟回调,在修改数据之后使用$nextTick,则可以在回调中获取更新之后的DOM。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>

<body>
    <div id="a1">
        <app></app>
    </div>
</body>

<script>
    var App={
        data:function(){
          return{
              is_show:false,
          }
        },
        template:'' +
        '<div>' +
            '<input type="text" v-if="is_show" ref="fos"/>'+
        '</div>',
        mounted(){
            this.is_show=true;
            // 在$nextTick函数中可以获取更新之后的DOM
            this.$nextTick(function () {
                this.$refs.fos.focus()
            })
            // console.log(this.$refs.fos) // undefined
            // this.$refs.fos.focus()
        }
    };

    new Vue({
        el:'#a1',
        data:{
        },
        components:{
            app:App,
        }
    });
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/fqh202/p/9645264.html