$refs的基本用法:
<div id="app">
<div ref="box">{{ msg }}</div>
<button @click = "change">点我改变msg的值</button>
<input type="text" ref="input1" id="input1">
<button @click="add">添加</button>
</div>
const app = new Vue({
el:"#app",
data:{
msg:'hello'
},
methods: {
change(){
//减少获取dom节点的消耗
//一般来讲,获取DOM元素,需document.querySelector(".box")获取这个dom节点,然后再获取元素的值。
//但是用ref绑定之后,就不需要再获取dom节点了,在js里面直接this.$refs.box里调用就行。
this.$refs.box.innerHTML = "hello world"
},
add(){
this.$refs.input1.value="222"
console.log(this.$refs.input1.value);
}
}
})
使用 this.$refs 来获取元素和组件
<!-- ref 需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。
比如在生命周期 mounted(){} 钩子中调用,或者在 this.$nextTick(()=>{}) 中调用。 -->
<div id="app">
<div>
<input type="button" value="获取元素内容" @click="getElement">
<!-- 使用ref获取元素 -->
<h1 ref="myh1">这是一个大大的h1</h1>
<!-- 使用获取子组件 -->
<!-- 在 子组件中使用 ref属性,会将子组件添加到父组件的$refs对象中 -->
<my-com ref="mycom"></my-com>
</div>
</div>
Vue.component('my-com',{
template:'<h5>这是一个子组件<h5>',
data() {
return {
name:'子组件'
}
},
methods: {
show(){
console.log('show方法被执行了....')
}
},
})
var vm = new Vue({
el:"#app",
data:{
},
methods:{
getElement(){
//通过this.refs来获取元素
console.log(this.$refs.myh1.innerText);
//通过this.$refs来获取组件
console.log(this.$refs.mycom.name);
//父组件可以直接调用子组件的方法
this.$refs.mycom.show()
}
}
})