vue——34- ref 获取DOM元素和组件

版权声明:未经同意,不得随意转载转载 https://blog.csdn.net/lucky541788/article/details/83097081

在这里插入图片描述
html

<div id="app">
    <login ref="mylogin"></login>
    <input type="button" value="获取元素" @click="getElement" ref="mybtn">
    <h3 id="myh3" ref="myh3">hello world!</h3>
</div>

js

        let login = {
            template: '<h1>hei boy!</h1>',
            data(){
                return{
                    msg:'子组件的数据!'
                }
            },
            methods:{
                show(){
                    console.log('调用了子组件的方法!');
                }
            }
        };

        // 创建 Vue 实例,得到 ViewModel
        let vm = new Vue({
            el: '#app',
            data: {},
            methods: {
                getElement() {
                    //console.log(document.getElementById('myh3').innerText);//hello world!

                    //ref 是英文单词 【reference】值类型 和 引用类型
                    console.log(this.$refs.myh3.innerText);//hello world!
                    console.log(this.$refs.mybtn.value);//获取元素
                    console.log(this.$refs.mylogin.msg);//子组件的数据!
                    this.$refs.mylogin.show();//调用了子组件的方法!
                }
            },
            components:{
                login
            }
        });

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/83097081