1. 程式人生 > 實用技巧 >vue之refs

vue之refs

<!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></App>
    </div>
    <script src="./vue.js"></script>
    <script>
        Vue.component('Test', {
            data() {
                return {
                    msg: "Test元件",
                }
            },
            template: `
                <div>
                    <h3>{{msg}}</h3>    
                </div>
            `,
        })
        const App = {
            mounted(){
                // 1.如果給標籤新增ref,獲取的就是真實的DOM節點
                // 2.如果給子元件新增ref,獲取的是當前子元件物件
                console.log(this.$refs.btn);
                // 載入頁面,自動獲取焦點
                this.$refs.input.focus();
                console.log(this.$refs.test);
                
            },
            components: {},
            template: `
                 <div>
                    <Test ref='test'></Test>
                    <input type="text" ref='input'/>
                    <button ref='btn'>改變生死</button>
                </div>
            `,
        }
        new Vue({
            el: '#app',
            components: {
                App
            }
        })
    </script>
</body>
</html>