ref
的使用
<!-- `vm.$refs.p`將會是DOM結點 --> <p ref="p">hello</p> <!-- `vm.$refs.child`將會是子組件實例 --> <child-component ref="child"></child-component>
深刻理解
$refs
某組件的$refs
含有該組件的全部ref
,看下面的例子html
<div id="app"> <p ref="p">hello</p> <child-component ref="child"></child-component> </div> <script> Vue.component('child-component', { template: '<h1>child-component </h1>' }) let vm = new Vue({ el: '#app' }) </script>
從上圖中咱們很容易發現vm.$refs
返回了一個對象,這個對象內有兩個成員,包含了vm實例的全部refvm.$refs.p
是DOM 元素vm.$refs.child
是組件實例app
看下面的例子this
<div id="app"> <counter ref="child1" @change="handleChange"></counter> <counter ref="child2" @change="handleChange"></counter> <div>{{sum}}</div> </div> <script> // counter組件,實現每點擊一次,自增1 Vue.component('counter', { template: '<h3 @click="handleClick">{{count}}</h3>', data() { return { count: 0 } }, methods: { handleClick() { this.count += 1; this.$emit('change') } } }) let vm = new Vue({ el: '#app', data: { sum: 0 }, methods: { handleChange() { this.sum = this.$refs.child1.count + this.$refs.child2.count // 使用refs獲取子組件的數據 } } }) </script>