一、引言
jquery 简化操作 DOM 的过程;vue 不需要操作 DOM,只需要维护好数据(数据驱动视图)。在 vue 项目中,不建议使用 jquery 。
二、ref 的作用
ref 用来辅助开发者在不依赖 jquery 的情况下,获取 DOM 元素或组件的引用。每个 vue 的实例上,都包含一个 $refs 对象,里面存储着对应 DOM 元素或组件的引用。默认情况下,组件的 $refs 指向一个空对象 。
- ref 获取页面 DOM 元素
// App.vue
<template>
<div>
<div>
<!-- ref 获取页面dom引用-->
<h1 ref="myh1">App 根组件</h1>
<button @click="showThis">打印 this</button>
</div>
</div>
</template>
<script>
// 一个 vue 组件实例
export default {
data(){
return {}
},
methods:{
showThis(){
// this 指向当前vue 实例
console.log(this)
this.$refs.myh1.style.color= 'red'
}
}
}
</script>
- ref 引用组件实例,需要从父组件中调用子组件的方法
// Left.vue
<template>
<div>
left
<button @click="count += 1">+1</button>
<button @click="resetCount">重置</button>
</div>
</template>
<script>
export default {
name: "Left",
data(){
return {
count: 0
}
},
methods:{
resetCount(){
this.count =0
}
}
}
</script>
-------------------------------------------------------
// App.vue
<template>
<div>
<div>
<h1>App 根组件</h1>
<button @click="onReset">重置 left 的组件的 count 值为0</button>
</div>
<div class="box">
<!-- ref 获取组件 left 的实例引用-->
<Left ref="comLeft"></Left>
</div>
</div>
</template>
<script>
import Left from '@/components/Left'
// 一个 vue 组件实例
export default {
data(){
return {}
},
methods:{
onReset(){
console.log(this)
this.$refs.comLeft.resetCount()
}
},
components:{
Left
}
}
</script>
例子:初步实现按钮和文本的按需展示
// App.vue
<template>
<div>
<div>
<h1>App 根组件</h1>
<hr/>
<input type="text" v-if="inputVisible" @blur="showButton" ref="iptRef"/>
<button v-else @click="showInput">展示输入框</button>
</div>
</div>
</template>
<script>
// 一个 vue 组件实例
export default {
data(){
return {
// 控制输入框和按钮的按需切换
// 默认值为 false ,表示默认展示按钮,隐藏输入框
inputVisible: false
}
},
methods:{
showInput(){
// 1.切换布尔值,把文本框展示
this.inputVisible= true
// 2.让展示出来的文本框,自获取焦点
// $nextTick(cb) 页面重新渲染完毕后,执行cb函数
this.$nextTick(() =>{
this.$refs.iptRef.focus()
})
},
showButton(){
this.inputVisible= false
}
}
}
</script>