Vue使用ref 属性来获取DOM

注意,在父组件中可以使用this.$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>
    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
    <div class="app">
        <input type="button" @click="show" value="点击">
        <!-- 设置元素ref 属性 -->
        <h1 ref="chuandi">中国是伟大的祖国</h1>
        <hr>
        <log ref="mylog"></log>
    </div>


    <template id="log">
        <div>
            <input type="button" value="获取元素" @click="comfunc">
            <h1>你说的很对啊</h1>
        </div>
    </template>


    <script>
        var vm=new Vue({
            el:'.app',
            data:{},
            methods: {
                show(){
                    // 获取ref属性为chuandi的内部文本
                    console.log(this.$refs.chuandi.innerText);    //获取到了h1 元素的文本
                    console.log(this.$refs.mylog.name);     //获取到了子组件的data属性
                    console.log(this.$refs.mylog.add);     //获取到了子组件的方法
                    
                }
            },

            components:{
                log:{
                    template:'#log',
                data(){
                    return{
                        name:'duwei'
                    }
                },
                methods: {
                    add(){

                        console.log('调用了子组件的方法');
                        
    
                    },
                    comfunc(){
                        console.log(this.$refs.chuandi.innerText);   //报错 innerText没有定义, 子组件不能通过ref 来获取父组件的属性方法
                        // 需要使用props
                        
                    }
                },
                }
               
            }
        })
    </script>
</body>
</html>

 

posted @ 2019-10-11 15:50  WhiteSpace  阅读(9373)  评论(0编辑  收藏  举报