gpt4 book ai didi

d3.js - 如何在 vue js 方法中捕获 svg 元素悬停事件以及如何将原生 javascript 悬停事件组合到 vue 方法

转载 作者:搜寻专家 更新时间:2023-10-30 22:16:43 24 4
gpt4 key购买 nike

我之前开发过vuejs + d3.js + jit库项目。现在,我需要将悬停功能附加到 d3.js svg 元素以显示悬停元素信息的弹出对话框。我按照一些 stackoverflow 说明尝试了很多次。但所有这些都不适合我的。这是我的代码片段。

allNodes.append("circle").attr("@mouseover", "console.log('test');");
allNodes.append("circle").attr(":v-on:mouseover", "console.log('dfdfd');");

上面的代码无论如何都不起作用,因为 d3.js 元素是在 vue 组件挂载时渲染的,vue 模板解析器无法编译 v-on,@mouseover 属性。

但是下面的代码工作正常。

allNodes.append("circle").attr("onmouseover", "console.log('test');");

所以我想我应该将原生 javascript 函数附加到 vue 方法以显示弹出对话框。

但我不确定如何配置所有项目结构以及在我的项目中将 native 函数放置在何处。

请帮帮我。

谢谢。

最佳答案

您可以在 d3 选择上使用 .on("mouseover", this.vueMethod),其中 this.vueMethod 在 Vue 组件的 methods< 中定义 对象。

new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn Vue", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
],
todoHovered: "hover a circle"
},
mounted() {
const svg = d3.select(this.$refs.chart)
.append("svg")
.attr("width", 400)
.attr("height", 100);
const circles = svg.selectAll("circle")
.data(this.todos).enter()
.append("circle")
.attr("cx", 10)
.attr("cy", (d,i) => 10 + i * 15)
.attr("r", 5)
.style("fill", d => d.done ? "green" : "red");
circles.on("mouseover", this.showMessage);
circles.on("mouseout", (e) => d3.select(e.currentTarget).attr("r", 5));
},
methods: {
showMessage(e, d) {
d3.select(e.currentTarget).attr("r", 8);
this.todoHovered = `${d.text} is ${d.done ? 'done' : 'not done'}`;
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

<div id="app">
<div ref="chart">
</div>
<p>
Message: {{ todoHovered }}
</p>
</div>

关于d3.js - 如何在 vue js 方法中捕获 svg 元素悬停事件以及如何将原生 javascript 悬停事件组合到 vue 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com