前言
之前对于ref的理解一直是通过该属性可以获取dom元素,后来才知道除了可以获取dom元素也可以用在组件当中
ref获取dom元素
vue是不直接操作dom元素的,但是有时候确实会用到那么怎么办?可以使用原始的js,也可以使用jQuery;但是vue为我们提供了ref这个属性
实例
<div id="app">
<p ref="pp">使用ref获取dom元素</p>
<button type="button" @click="getInfo">点击</button>
</div>
<script type="text/javascript">
new Vue({
el:'#app',
methods:{
getInfo(){
alert("p标签中的内容是:"+this.$refs['pp'].innerText)
}
}
})
</script>
1、在标签上添加一个ref属性,然后为这个属性起一个别名
2、通过this.$refs['别名']
可以获取到这个元素
3、除了数组方式也可以使用对象方法this.$refs.属性名
,不过建议使用数组方式
ref获取组件
实例
<div id="app">
<child ref="child"></child>
<button type="button" @click="getInfo">获取组件中的属性</button>
<button type="button" @click="getFunction">调用组件中的方法</button>
</div>
<script type="text/javascript">
//定义组件
Vue.component('child',{
template:`
<div style="width:200px;height:200px;border:1px solid;">
<h2>组件</h2>
<p>{{info}}</p>
<button type="button" @click="showInfo">组件内部的方法</button>
</div>
`,
data(){
return {
info:'使用ref获取组件'
}
},
methods:{
showInfo(){
alert(this.info)
}
}
})
new Vue({
el:'#app',
methods:{
getInfo(){
alert("组件中info属性的值是:"+this.$refs['child'].info)
},
getFunction(){
this.$refs['child'].showInfo()
}
}
})
</script>
1、在组件上添加一个ref属性,并为这个组件起一个别名
2、通过this.$refs['别名']
可以获取到这个组件。当获取到组件后,你可以得到组件中的属性,也可以调用组件中的方法