Vue中鼠标移入移出事件
@mouseover和@mouseleave 然后绑定style
现在开始代码示例
<template> <div class="pc"> <h1>{{ msg }}</h1> <div class="demo" @mouseover="mouseOver" @mouseleave="mouseLeave" :style="active" > <p ref="acp">我是内容</p> </div> </div> </template> <script> export default { name: "HelloWorld", data() { return { msg: "HelloWorld,I am PC", active: "", }; }, methods: { // 移入 mouseOver() { this.active = "background-color:black"; // 操作dom 获取p标签改变其样式 var acps = this.$refs.acp acps.style.color = "red" }, // 移出 mouseLeave() { this.active = ""; this.$refs.acp.style='' } } }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style lang="scss" scoped> .pc { .demo { width: 100%; height: 300px; background-color: lightcoral; p { color: limegreen; } } } </style>
1、给需要使用移入移出事件的添加事件:
@mouseover @mouseleave
2、绑定style 这个 `active` 是绑定名 可以自己随意更换
:style="active"
3、在 data 里定义 绑定的类名
data() {
return {
msg: "HelloWorld,I am PC",
active: "",
};
},
4、在 methods 里定义事件 要改变内部的元素 通过ref 操作dom
methods: {
mouseOver() {
this.active = "";
var acps = this.$refs.acp
acps.style.color="red"
},
mouseLeave() {
this.active = "";
this.$ref.acp.style=''
}
}
这样移入移出就完成了
所有评论(0)