1挺尿、ref 加在普通的元素上斜做,用this.$refs.(ref的值) 獲取到的是dom元素
<div id="app">
<div ref="haha">這是div</div>
<button @click="getref">獲取H1元素</button>
</div>
methods: {
getref() {
console.log(this.$refs.haha.innerText);// 表示從 $refs對象 中, 獲取 ref 屬性值為haha的DOM元素
this.$refs.haha.style.color = 'green';// 修改html樣式
}
}
2、ref 加在子組件上舷夺,用this.
refs.(ref的值).方法() 就可以使用了。
父組件
<template>
<div>
<button @click="clickParent">點擊</button>
<child ref="mychild"></child>
</div>
</template>
<script>
import Child from "./child";
export default {
name: "parent",
components: {
child: Child
},
methods: {
clickParent() {
this.$refs.mychild.parentHandleclick("嘿哈嘿"); // 劃重點1拧O入g衷!
}
}
};
</script>
子組件
<template>
<div>
child
</div>
</template>
<script>
export default {
name: "child",
props: "someprops",
methods: {
parentHandleclick(e) {
console.log(e);
}
}
};
</script>
3喳魏、如何利用 v-for 和 ref 獲取一組數(shù)組或者dom 節(jié)點
ref 是循環(huán)出來的棉浸,有多個重名,那么ref的值會是一個數(shù)組 刺彩,此時要拿到單個的ref 只需要循環(huán)就可以了迷郑。