目的
通过设置scss中的样式选择器变量,修改vue中的变量中的变量动态设置样式
代码
<template>
<div>
<span class="targetClass" :isFocus="isFocus">这是目标要素</span>
<div class="otherClass" @click="setIsFocus"></div>
</div>
</template>
<script>
export default {
components: {},
props: {},
data() {
return {
isFocus: false,
};
},
watch: {},
computed: {},
methods: {
//设置样式选择器是否生效
setIsFocus() {
event.stopPropagation();
this.isFocus = !this.isFocus;
},
//设置啥时候解除点击事件
useStyleChange() {
const fnc = (e) => {
this.isFocus = false;
};
document.body.addEventListener("click", fnc);
this.$on("hook:beforeDestroy", () => {
document.body.removeEventListener("click", fnc);
});
},
},
created() {
this.useStyleChange();
},
mounted() {},
};
</script>
<style lang="scss" scoped>
.targetClass {
background-color: black;
&[isFocus="true"] {
background-color: red;
}
}
.otherClass {
width: 500px;
height: 500px;
border: 1px black solid;
}
</style>
解析:
通过动态设置isFocus的值,来控制scss样式选择器中匹配的值,找到对应的样式;在界面关闭的时候,在解除掉点击事件的监听;