一、位置

生命周期的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>

 

相关文章:

  • 2021-07-08
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-07-31
猜你喜欢
  • 2022-12-23
  • 2021-08-14
  • 2021-05-20
  • 2022-12-23
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案