在v-for循環中使用ref會用一個問題,如果使用綁定 :ref 會發現,使用js是無法對綁定的元素進行操作的,原因在vue官網中有說明。但是還是希望能夠在v-for中使用ref並且能夠使用js對每個元素進行操作,這裏就不要使用綁定的方式。下面給出了v-for中使用兩種不同方式的實驗結果,使用綁定的方式會報錯,不使用綁定的方式可以操作成功。
1、v-for中使用ref,綁定的方式
<template>
<div>
<div class="main" @click="test">
<div id="animateDiv" class="normal"></div>
</div>
<div :ref="'dd' + n" v-for="n in 10" class="dddd">{{n}}</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {};
},
methods: {
test() {
let animateDiv = document.getElementById("animateDiv");
animateDiv.classList.add("animate");
console.log(this.$refs)
this.$refs.dd1.style.background="#FF0000"
// console.log(this.$refs.dd)
// this.$refs.dd['0'].style.background="#FF0000"
}
}
};
</script>
<style lang='less'>
.main {
height: 400px;
width: 400px;
padding: 10px;
border: 2px solid silver;
}
.normal {
height: 200px;
width: 200px;
background: lightcoral;
transition: 1s;
}
.animate {
height: 100%;
width: 100%;
background: silver;
}
.dddd {
.main;
background: green;
}
</style>
2、不使用綁定
<template>
<div>
<div class="main" @click="test">
<div id="animateDiv" class="normal"></div>
</div>
<div ref="dd" v-for="n in 10" class="dddd">{{n}}</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {};
},
methods: {
test() {
let animateDiv = document.getElementById("animateDiv");
animateDiv.classList.add("animate");
// console.log(this.$refs)
// this.$refs.dd1.style.background="#FF0000"
console.log(this.$refs.dd)
this.$refs.dd['0'].style.background="#FF0000"
}
}
};
</script>
<style lang='less'>
.main {
height: 400px;
width: 400px;
padding: 10px;
border: 2px solid silver;
}
.normal {
height: 200px;
width: 200px;
background: lightcoral;
transition: 1s;
}
.animate {
height: 100%;
width: 100%;
background: silver;
}
.dddd {
.main;
background: green;
}
</style>