从 jQuery 转换为 Vue? [英] Convert from jQuery to Vue?
问题描述
我想转换以下 javascript 代码:
I would like to transform the following code which is in javascript:
$('a').click(function() {
$(this).find('i').toggleClass('fa-heartbeat');
});
在 vue.js 中.
in vue.js.
函数名:like
javascript 测试:https://jsfiddle.net/jsk590ep/
javascript test: https://jsfiddle.net/jsk590ep/
推荐答案
在 Vue 中,您通常不会直接选择和操作 DOM 元素,而是将数据绑定到 Vue 组件中的部分标记.
In Vue, you typically don't select and manipulate DOM elements directly, you rather bind data to parts of the markup within your Vue components.
也就是说:你甚至不需要一个函数.简单的
That said: You don't even need a function for that. Simply
- 添加指示图标所处状态的数据元素(参见https://vuejs.org/v2/guide/#Declarative-Rendering)
- 在周围
a
的@click
处理程序中更改其值,请参阅 https://vuejs.org/v2/guide/events.html#Listening-to-Events - 根据状态将
fa
类有条件地绑定到图标上,参见https://vuejs.org/v2/guide/class-and-style.html
- add a data element that indicates which state the icon is in (see https://vuejs.org/v2/guide/#Declarative-Rendering)
- change its value in the
@click
handler of the surroundinga
, see https://vuejs.org/v2/guide/events.html#Listening-to-Events - conditionally bind the
fa
classes based on the state to the icon, see https://vuejs.org/v2/guide/class-and-style.html
<a href="#" @click="liked = !liked">
<i :class="['fa', liked ? 'fa-heartbeat' : 'fa-plus-circle']"></i>
</a>
查看 vue 文档时,请注意示例中的 @click
是 v-on:click
和 :class
的快捷方式对于 v-bind:class
.
When looking at the vue docs, note that @click
in the example is a shortcut for v-on:click
and :class
for v-bind:class
.
这里的工作示例:https://codesandbox.io/s/stack-overflow-q-57403395-ul62e?module=/src/App.vue
这篇关于从 jQuery 转换为 Vue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!