Vue ref

一、位置

生命周期的mounted

二、作用

1、获取原始的DOM

给input标签添加focus属性

<!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">
        <App />
    </div>
    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        let App = {
            data(){
                return {
                    msg: "测试"
                }
            },
            template: `
                <div>
                    <p>{{msg}}</p>
                    <input type="text" ref="test">    
                </div>
            `,
            mounted(){
                var temp = this.$refs.test;
                console.log(temp);  // <input type="text"> 原始DOM资源
                temp.focus();
            }
        }
        new Vue({
            el: "#app",
            data(){
                return {

                }
            },
            components:{
                App
            }

        })
    </script>
</body>
</html>

2、获取组件实例化对象

<!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">
        <App ref="foo"></App>
    </div>
    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        let App = {
            data(){
                return {
                    msg: "测试"
                }
            },
            template: `
                <div>
                    <p>{{msg}}</p>
                    <input type="text" ref="test">    
                </div>
            `,
            mounted(){
                var temp = this.$refs.test;
                // console.log(temp);  // <input type="text"> 原始DOM资源
                temp.focus();
            }
        }
        new Vue({
            el: "#app",
            data(){
                return {

                }
            },
            components:{
                App
            },
            // 箭头函数的单体对象
            mounted(){
                var temp = this.$refs.foo;
                console.log(temp); // VueComponent
            }

        })
    </script>
</body>
</html>

 

posted @ 2019-09-11 23:25  市丸银  阅读(204)  评论(0编辑  收藏  举报