zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    转载__Java内部类
    Fragment之介绍(转)
    转载__Android-屏幕适配需要注意的地方
    转载__广播机制
    Activity的启动模式--总结
    图片_ _Android--加载大分辨率图片到内存
    转载—— android 瀑布流的实现详解,附源码
    转载_安卓性能优化
    C# Byte[] 数组操作
    C# 测算代码运行时间 Stopwatch
  • 原文地址:https://www.cnblogs.com/xiaowie/p/11654693.html
Copyright © 2011-2022 走看看