Vue中$refs的用法詳解
更新時間:2018年06月24日 08:38:14 作者:果凍丨小布丁
這篇文章主要介紹了Vue中$refs的用法,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下
說明:vm.$refs 一個對象,持有已注冊過 ref 的所有子組件(或HTML元素)
使用:在 HTML元素 中,添加ref屬性,然后在JS中通過vm.$refs.屬性來獲取
注意:如果獲取的是一個子組件,那么通過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的用法詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大的!
相關(guān)文章
Vuepress 搭建帶評論功能的靜態(tài)博客的實現(xiàn)
這篇文章主要介紹了Vuepress 搭建帶評論功能的靜態(tài)博客的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-02-02