Vue中$refs的用法詳解
更新時(shí)間:2018年06月24日 08:38:14 作者:果凍丨小布丁
這篇文章主要介紹了Vue中$refs的用法,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下
說明:vm.$refs 一個(gè)對(duì)象,持有已注冊(cè)過 ref 的所有子組件(或HTML元素)
使用:在 HTML元素 中,添加ref屬性,然后在JS中通過vm.$refs.屬性來獲取
注意:如果獲取的是一個(gè)子組件,那么通過ref就能獲取到子組件中的data和methods
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <!-- <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> --> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <style> </style> </head> <body> <div id="vue_app"> <qinwm ref="vue_qinwm"></qinwm> <p ref="vue_p">Hello, world!</p> <button @click="getRef">getRef</button> </div> </body> </html> <script> Vue.component("qinwm", { template: `<h1>{{msg}}</h1>`, data(){ return { msg: "Hello, world!" }; }, methods:{ func:function (){ console.log("Func!"); } } }); new Vue({ el: "#vue_app", data(){ return {}; }, methods: { getRef () { console.log(this.$refs); console.log(this.$refs.vue_p); // <p>Hello, world!</p> console.log(this.$refs.vue_qinwm.msg); // Hello, world! console.log(this.$refs.vue_qinwm.func); // func:function (){ console.log("Func!"); } this.$refs.vue_qinwm.func(); // Func! } } }); </script>
總結(jié)
以上所述是小編給大家介紹的Vue中$refs的用法詳解,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大的!
相關(guān)文章
Vue keep-alive實(shí)踐總結(jié)(推薦)
本篇文章主要介紹了Vue keep-alive實(shí)踐總結(jié)(推薦),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08vue的props實(shí)現(xiàn)子組件隨父組件一起變化
這篇文章主要為大家詳細(xì)介紹了vue的props如何實(shí)現(xiàn)子組件隨父組件一起變化,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10Vuepress 搭建帶評(píng)論功能的靜態(tài)博客的實(shí)現(xiàn)
這篇文章主要介紹了Vuepress 搭建帶評(píng)論功能的靜態(tài)博客的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02