ref定义值, 通过 $refs.值 来获取dom或组件对象
1获取原生的DOM标签
<template>
<div>
<h1 ref="myH">1. ref获取原生dom</h1>
<button @click="fn">点击修改上面内容</button>
</div>
</template>
<script>
export default {
methods: {
fn() {
console.log(this.$refs.myH1);
this.$refs.myH1.innerHTML = "改内容了";
}
}
}
</script>
2获取组件对象,然后可以为所欲为
<div>
<p :style="{ color: ind == 0 ? 'red' : '' }">首页</p>
<p :style="{ color: ind == 1 ? 'red' : '' }">分类</p>
<p :style="{ color: ind == 2 ? 'red' : '' }">爱好</p>
</div>
</template>
<script>
export default {
data() {
return {
ind: 0,
};
},
methods: {
changeIndex(index) {
this.ind = index;
},
},
};
</script>
<style>
</style>
<h1>2. 调用demo组件方法</h1>
<button @click="fn2">点击demo组件里最后一个高亮</button>
<Demo ref="de"></Demo>
<script>
import Demo from "./components/Demo";
export default {
components: {
Demo,
},
methods: {
fn2() {
this.$refs.de.changeIndex(2);
},
},
};
</script>