从 jQuery 转换为 Vue? [英] Convert from jQuery to Vue?

查看:48
本文介绍了从 jQuery 转换为 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

  • 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 surrounding a, 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 文档时,请注意示例中的 @clickv-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆