作用:利用ref和$refs可以用于获取dom元素或组件实例
特点:在当前组件内查找(更精确更稳定)
1.获取dom元素:
首先给目标元素添加ref属性
然后通过this.$refs.xxx获取目标标签
<template>
<div ref="mychart" class="base-chart-box"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
mounted() {
// 基于准备好的dom,初始化echarts实例
const myChart = echarts.init(this.$refs.mychart);
// 绘制图表
myChart.setOption({
title: {
text: "ECharts 入门示例",
},
tooltip: {},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
});
},
};
</script>
<style scoped>
.base-chart-box {
width: 400px;
height: 300px;
border: 3px solid #000;
border-radius: 6px;
}
</style>
2.获取组件:
首先给目标组件添加ref属性
然后通过this.$refs.xxx获取目标组件
子组件:
<template>
<div class="app">
<div>账号: <input v-model="account" type="text" /></div>
<div>密码: <input v-model="password" type="text" /></div>
<div></div>
</div>
</template>
<script>
export default {
data() {
return {
account: "admin",
password: "123456",
};
},
methods: {
//方法一:收集表单数据,返回一个对象
getValues() {
return {
account: this.account,
password: this.password,
};
},
//方法二:重置表单
resetValues() {
this.account = "";
this.password = "";
console.log("重置表单数据成功");
},
},
};
</script>
<style scoped>
.app {
border: 2px solid #ccc;
padding: 10px;
}
.app div {
margin: 10px 0;
}
.app div button {
margin-right: 8px;
}
</style>
父组件:
<template>
<div class="app">
<BaseForm ref="baseForm"></BaseForm>
<button @click="handleGet">获取数据</button>
<button @click="handlereset">重置数据</button>
</div>
</template>
<script>
import BaseForm from "../vue-project/src/components/BaseForm.vue";
export default {
components: {
BaseForm,
},
methods: {
handleGet() {
//可以调用子组件的方法
console.log(this.$refs.baseForm.getValues());
},
handlereset() {
this.$refs.baseForm.resetValues();
},
},
};
</script>
<style>
</style>
vue是异步更新DOM(提升性能)
$nextTick等DOM更新后,才会触发执行此方法里的函数体
<template>
<div class="app">
<div v-if="isShowEdit">
<input ref="inp" type="text" v-model="editValue" />
<button>确认</button>
</div>
<div v-else>
<span>{{ title }}</span>
<button @click="handleEdit">编辑</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
title: "大标题",
isShowEdit: false,
editValue: "",
};
},
methods: {
handleEdit() {
//1.显示输入框(异步dom更新)
this.isShowEdit = true;
//2.让输入框获取焦点
this.$nextTick(() => {
this.$refs.inp.focus();
});
},
},
};
</script>
<style>
</style>