前面也提到過,Vue是不提倡用原生js或者第三方庫【jquery】去獲取並操作dom元素的。但是這種需求不可避免,Vue官網提供了一個ref屬性,用於我們在自定義方法中去獲取具有這個ref屬性的元素。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> <script src="../js/vue-router.js"></script> </head> <style> </style> <body> <div id="app"> <h3 ref='thish3'>這是一個h3標簽</h3> <hr> <template1 ref='mycom'> //模板也可以標記ref,然后獲取到 </template1> <input type="button" value="獲取dom元素或組件" @click='getelement'> </div> <!-- 注意,組件也可以被$refs引用 --> </body> <script> let template1 = { template: '<h1>這是h1</h1>', data: function() { return { id: 1, val: 'hhh' } }, methods: { myfunc() { console.log('這是一個方法') } } } let vm = new Vue({ el: '#app', data: { }, methods: { getelement() { console.log(this.$refs.mycom.val);//調用組件里的val this.$refs.mycom.myfunc() //引用組建后,可以使用$refs.引用組件時設置的ref屬性.組件內容來獲取被引用組件的數據和函數 } }, components: { template1 } }) </script> </html>
可以看到,這個ref屬性非常強大,只要加上ref屬性,就可以在Vue實例通過$refs獲取到,父組件就可以輕松的得到子組件里面的內容【$emit('func_name',{}),通過觸發父組件里的方法,然后傳值到方法中的這種方式明顯就繁瑣而且多個數據的傳遞還需要經過-壓入到一個對象中的這種處理才能傳遞】。