像往常一样给标签写一个id然后在里面getElementById是不行的,会提示:
Cannot read property ‘classList’ of null
读取到空值云云……
在VUE中需要使用 ref 和 $refs 来操作:
<template>
<div ref="myDiv" class="box" @click="changecolor">点我点我</div> //看这里
</template>
<script>
export default {
data() {
return {};
},
methods: {
changecolor() {
this.$refs.myDiv.style.backgroundColor = "red" ; //看这里,注意大小写
},
},
};
</script>
<style>
.box{
height: auto;
width: 300px;
margin: 0 auto;
font-size: 50px;
text-align: center;
}
</style>
这样就不会报错啦。