Vue之獲取DOM元素與更新DOM后事件的特殊情況


 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

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

    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>
       
       /*
       在Vue中提供了一種特別的方式來獲取元素:
       給元素加上個ref屬性,那么就可以通過this.$refs.名字來獲取到該元素
       */

       /* 前面知道了Vue的生命周期的鈎子函數,其中需要注意的是在DOM掛載后,事件可能不能正常的觸發,
       需要將其放入到$nextTick方法里:在下次 DOM 更新循環結束之后執行延遲回調。
       在修改數據之后立即使用這個方法,獲取更新后的 DOM。
       */

       new Vue({
           el: '#app',
           data(){
                return {
                    isShow: false
                }
           },
           template:`
           <div>
            <input type='text' v-if='isShow' ref='inp'/>
            </div>
           `,
            mounted() {
                this.isShow = true;
                // 若刪掉外面的$nextTick方法,那么將不能識別出該輸入框,
                // 聚焦事件也不能正常執行
                this.$nextTick(function() {
                    console.log(this.$refs.inp);
                    this.$refs.inp.focus();
                });
            }
       })

    </script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM