注意,在父組件中可以使用this.$refs.屬性名 獲取任何元素的屬性和方法,子組件不可以獲取父組件中的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div class="app"> <input type="button" @click="show" value="點擊"> <!-- 設置元素ref 屬性 --> <h1 ref="chuandi">中國是偉大的祖國</h1> <hr> <log ref="mylog"></log> </div> <template id="log"> <div> <input type="button" value="獲取元素" @click="comfunc"> <h1>你說的很對啊</h1> </div> </template> <script> var vm=new Vue({ el:'.app', data:{}, methods: { show(){ // 獲取ref屬性為chuandi的內部文本 console.log(this.$refs.chuandi.innerText); //獲取到了h1 元素的文本 console.log(this.$refs.mylog.name); //獲取到了子組件的data屬性 console.log(this.$refs.mylog.add); //獲取到了子組件的方法 } }, components:{ log:{ template:'#log', data(){ return{ name:'duwei' } }, methods: { add(){ console.log('調用了子組件的方法'); }, comfunc(){ console.log(this.$refs.chuandi.innerText); //報錯 innerText沒有定義, 子組件不能通過ref 來獲取父組件的屬性方法 // 需要使用props } }, } } }) </script> </body> </html>
