【发布时间】:2018-09-20 22:14:12
【问题描述】:
我是 Vue.js 的新手,需要创建一个 Vue 组件来创建和操作 SVG。据我了解,最好在 Vue 组件中使用 JQuery。但是我想这样做,因为选择元素非常简单。
这是我的 Vue 组件,但我不知道如何使它起作用。 (注意:SVG 将来自 Web 服务,因此我需要以编程方式将其附加到 DOM。)
<div id="app">
<p>Hover mouse over the lights to turn them on.</p>
<p>(How do I make this work??)</p>
<div id="svg-div" v-html="svg" />
</div>
new Vue({
el: '#app',
data: {
svg: `
<svg width="50" height="120">
<rect x="10" y="10" width="40" height="120" style="fill:black" />
<circle cx="30" cy="30" r="15" fill="red" opacity=".3"/>
<circle cx="30" cy="65" r="15" fill="yellow" opacity=".3"/>
<circle cx="30" cy="100" r="15" fill="lightgreen" opacity=".3"/>
</svg>`
}
})
这是一个使用 JQuery 的工作示例(非 Vue)。
var svg = `
<svg width="50" height="120">
<rect x="10" y="10" width="40" height="120" style="fill:black" />
<circle cx="30" cy="30" r="15" fill="red" opacity=".3"/>
<circle cx="30" cy="65" r="15" fill="yellow" opacity=".3"/>
<circle cx="30" cy="100" r="15" fill="green" opacity=".3"/>
</svg>
`;
$('#svg-div').html(svg);
$('circle').mouseenter(function() {
$(this).attr('opacity', '1');
});
$('circle').mouseleave(function() {
$(this).attr('opacity', '.3');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hover mouse over the lights to turn them on.</p>
<div id="svg-div" />
【问题讨论】:
-
你是对的,jQuery 和 Vue 不能很好地混合在一起,因为 Vue 的方法是(几乎)从不自己操作 dom,而是让 vue 渲染器为你完成工作,而你只不得不担心数据。根据您的描述,您希望在此示例中实现的目标可以使用 css 轻松完成,并且更具声明性。在这种情况下有什么反对使用 css 的吗? (见这个例子:codepen.io/anon/pen/EEMwbg)