首页 > 其他 > 详细

Vue ref的使用

时间:2021-07-17 10:54:15      阅读:26      评论:0      收藏:0      [点我收藏+]

ref的使用还是比较简单的,就是在Vue中可以操作DOM

分为以下两种情况:

1.通过ref操作html标签

下面的代码中,会打印"refP"

<div id="app">
        <button @click="getRef()">获取标签ref</button>
        <p ref="refP">refP</p>
</div>
<script>
        const app = new Vue({
            el: ‘#app‘,
            data() {
                return {
                    
                }
            },
            methods: {
                getRef: function() {
                    console.log(app.$refs.refP.innerHTML);
                }, 
            },
        })
</script>

2.通过ref操作组件

下面的代码中,会打印“组件Ref"

<div id="app">
        <button @click="getRef2">获取组件ref</button>
        <test-ref ref="refCom">refCom</test-ref>
    </div>
    <script>
        Vue.component(‘test-ref‘, {
            template: `<div><div>componentRef</div><div>{{test}}</div></div>`,
            data() {
                return {
                    test: ‘组件Ref‘
                }
            }
        })
        const app = new Vue({
            el: ‘#app‘,
            methods: {
                getRef2: function() {
                    console.log(app.$refs.refCom.test);
                }
            },
            components: {
                testref: ‘test-ref‘
            }
        })
    </script>

  

Vue ref的使用

原文:https://www.cnblogs.com/jnuallen/p/15022138.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!