7 $ref和$nextTick

编辑本文章

1、$ref

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>09-原生DOM操作</title>
</head>
<body>

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

<script src="./node_modules/vue/dist/vue.js"></script>

<script type="application/javascript">
    var App = {
        template: `<div>
                    <button ref="btn">我是按钮</button>
                  </div>`,
        beforeCreate() {
            //this都还没创建
        },
        created() {
            //创建完成,但是还没挂载,还是虚拟DOM,所以拿不到DOM对象
        },
        beforeMount() {
            //同created一样
        },
        mounted() {
            console.log(this.$refs.btn);
            var _this=this;
            this.$refs.btn.onclick=function () {
                console.log("调用按钮原生onclick属性");
                console.log(_this.$refs.btn.innerHTML);
                console.log(_this)
            }
        }
    };
    new Vue({
        el: "#app",
        template: `<App/>`,
        data() {
            return {}
        },
        components: {
            App
        },
        methods: {},
        computed: {}
    })
</script>
</body>
</html>
View Code

 

$ref,给对象一个ref属性,就可以在Vue实例中通过$refs来获取该DOM。

如果给组件绑定ref="subc"属性,通过this.$refs.subc拿到的是组件对象

$refs:获取组件内的元素

$parent:获取当前元素的父组件

$children:获取当前组件子组件

$root:获取new Vue的实例化对象

$el:获取组件对象的DOM元素

2、$nextTick

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>10-给DOM元素添加事件的特殊情况</title>
</head>
<body>

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

<script src="./node_modules/vue/dist/vue.js"></script>

<script type="application/javascript">
    var App = {
        template: `<div>
                    <input type="text" ref="fos" v-if="isShow"></input>
                  </div>`,
        data(){
            return {
                isShow:false
            }
        },
        mounted() {
            this.isShow=true;
            //这样拿不到DOM
            //this.$refs.fos.focus()
            this.$nextTick(function () {
                //这里才能获取更新之后的DOM
                this.$refs.fos.focus();
            })
        }
    };
    new Vue({
        el: "#app",
        template: `<App/>`,
        data() {
            return {}
        },
        components: {
            App
        },
        methods: {},
        computed: {}
    })
</script>
</body>
</html>
View Code

 

数据更新后,DOM并不是立即发生变化,而是按一定策略进行DOM的更新。

$nextTick是在下次DOM更新循环结束之后执行的延迟回调,在修改数据之后使用该方法,则可以在回调中获取更新之后的DOM

posted @ 2019-06-11 19:32  丫丫625202  阅读(241)  评论(0编辑  收藏  举报