ref基础使用
给div标签添加一个ref属性。
<div ref="colorboxref" style="width: 200px;height: 200px">这里是什么颜色??</div>
在方法中通过$rerfs和ref的值来获得div的DOM
changeColor() {
console.log("hello")
this.$refs.colorboxref.style.color = "red"
// this.$refs["color-box-ref"].color = "red"
}
通过ref父组件获得子组件的DOM
给子组件加上ref属性,通过$refs来获得子组件。
可以获得子组件的data和methods。
<Test ref="testref"></Test>
this.$refs.testref.color="green"
this.$refs.testref.printColor()
this.$nextTick
有一种特殊情况,当触发某个事件时,需要同时修改data和操作DOM元素。但是vue在data修改后会重新渲染界面,如果渲染界面时需要重新生成一个标签,但是渲染未完成导致标签的DOM无法操作,此时需要一个延迟执行。
//展示一个输入框,在渲染完成后才可以操作输入框的DOM元素
this.isInput = true
//延迟至到渲染结束DOM元素生成时再操作DOM
this.$nextTick(()=>{
this.$refs.inputRef.focus()
})