1. 基本用法:在当前页面中获取dom元素
<div id="app">
<button @click="getRef" ref="button">获取该节点</button>
</div>
<script>
new Vue({
el:'#app',
methods:{
getRef(){
console.log(this.$refs.button)
}
}
});
</script>
2. 获取子组件中的data
<div id="app1">
<child @click.native="getChildData" ref="data"></child>
</div>
<script>
Vue.component('child',{
data(){
return{
msg:'hello'
}
},
template:'<button>获取子组件中的data</button>'
})
new Vue({
el:'#app1',
methods:{
getChildData(){
console.log(this.$refs.data.msg)
}
}
});
</script>
3. 获取子组件中的方法
<div id="app2">
<button @click="getChildMethod">获取子组件中的方法</button>
<child-a ref="meth"></child-a>
</div>
<script>
Vue.component('child-a',{
methods:{
method(){
console.log('调用成功')
}
},
template:'<div></div>'
})
new Vue({
el:'#app2',
methods:{
getChildMethod(){
this.$refs.meth.method()
}
}
});
</script>
4. 子组件调用父组件的方法
例一:
<div id="root">
<counter ref="one" @change="handleChange"></counter>
<counter ref="two" @change="handleChange"></counter>
<div>{{total}}</div>
</div>
<script>
Vue.component('counter',{
template: '<div @click="handleClick">{{ number }}</div>',
data: function(){
return {
number: 0
}
},
methods: {
handleClick: function () {
this.number ++
this.$emit('change')
}
}
})
var vm =new Vue({
el: "#root",
data: {
total: 0
},
methods: {
handleChange: function () {
this.total= this.$refs.one.number + this.$refs.two.number
console.log(this.$refs.one.number)
console.log(this.$refs.two.number)
}
}
})
例二:
<div id="app3">
<child-b ref="hello" @refresh="getData"></child-b>
<button @click="getFatherMethod">按钮</button>
</div>
<script>
Vue.component('child-b',{
methods:{
open(){
console.log("111")
this.$emit('refresh')
}
},
template:'<div></div>'
})
new Vue({
el:'#app3',
methods:{
getFatherMethod(){
this.$refs.hello.open()
},
getData(){
console.log('调用成功')
}
}
});
</script>