首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

08 在Vue3中使用方法

概述

In Vue 2.0, Vue defines component methods inside the methods object as part of a Vue instance. You compose each component method as a normal JavaScript function. The Vue method is scoped to your Vue component and can be run from anywhere inside the component it belongs to. It also has access to the this instance, which indicates the instance of the component:

在 Vue 2.0 中,Vue 在 methods 对象中定义了组件方法,作为 Vue 实例的一部分。你可以将每个组件方法编译成一个普通的 JavaScript 函数。Vue 方法的作用域是您的 Vue 组件,可以在其所属组件的任何位置运行。它还可以访问 this 实例,该实例表示组件的实例:

export default {

methods: {

myMethod() { console.log('my first method'); }

}

}

From Vue 3.0 onward, with , as with local data, you can define a method as a regular function and it will work the same way as with the traditional approach. Hence, we can rewrite the preceding code as follows:

从 Vue 3.0 开始,使用 ,就像使用本地数据一样,可以将方法定义为普通函数,其工作方式与传统方法相同。因此,我们可以将前面的代码重写如下:

const myMethod = () => { console.log('my first method'); }

You then can bind the methods to HTML events of an element as its event listeners in the template section. When binding events to HTML elements in Vue, you would use the @ symbol. For example, v-on:click is equivalent to @click, as shown in the following code block:

然后,您就可以在模板部分将这些方法绑定到元素的 HTML 事件上,作为其事件监听器。在 Vue 中将事件绑定到 HTML 元素时,需要使用 @ 符号。例如,v-on:click 相当于 @click,如以下代码块所示:

Click me

Click me shorter

Clicking on both buttons triggers the same myMethod() method and generates the same result.

点击这两个按钮会触发相同的 myMethod() 方法,并产生相同的结果。

Let’s build a component with some methods.

让我们用一些方法构建一个组件。

练习:触发方法

In this exercise, we are going to build a component that uses Vue’s methods API. Consider how similarly these Vue methods can be written to your own named functions in JavaScript, as they behave in a very similar way. By the end of the exercise, we should be able to use methods and trigger them from the HTML template.

在本练习中,我们将构建一个使用 Vue 方法 API 的组件。考虑一下这些 Vue 方法的编写方式与您自己在 JavaScript 中命名的函数是多么相似,因为它们的行为方式非常相似。练习结束时,我们应该能够使用方法并从 HTML 模板中触发它们。

Create a new Vue component file named Exercise1-08.vue in the src/components directory.

在 src/components 目录中新建一个名为 Exercise1-08.vue 的 Vue 组件文件。

修改App.vue,引入该组件并渲染:

import Exercise from "./components/Exercise1-08.vue";

Inside Exercise1-08.vue, within the section, let’s define a method, triggerAlert, that receives an index and displays an alert informing users which index has been clicked:

在 Exercise1-08.vue 的 部分,让我们定义一个方法 triggerAlert,该方法接收一个索引并显示一个提示,告知用户点击了哪个索引:

const triggerAlert = (index) => {

alert(`${index} has been clicked`)

}

In the template section, set up an anonymous v-for loop on an HTML list and add a button element inside the list element. Set the loop to iterate 5 times, and display the index value as each button’s label:

在模板部分,在 HTML 列表中设置匿名 v-for 循环,并在列表元素中添加一个按钮元素。设置循环迭代 5 次,并将索引值显示为每个按钮的标签:

Triggering Vue Methods

Trigger {{ index }}

Add the @click directive, referencing the triggerAlert method, and pass the value of index as an argument:

添加 @click 指令,引用 triggerAlert 方法,并将 index 的值作为参数传递:

Triggering Vue Methods

Trigger {{ index }}

Add a margin between each button for readability:

在每个按钮之间添加边距,以便阅读:

button {

margin: 10px;

}

NOTE: While you can add an event listener to any HTML element, we suggest applying them to native HTML interactive elements such as anchor tags, form input, or buttons to help with browser accessibility.

注意:虽然您可以为任何 HTML 元素添加事件监听器,但我们建议将其应用于本地 HTML 交互式元素,如锚标记、表单输入或按钮,以帮助实现浏览器的可访问性。

At this point, you can utilize the Vue methods API to define and trigger methods from the HTML template, and parse arguments into each method dynamically. In the next exercise, we will explore how to return data with Vue methods within a Vue component.

此时,您可以利用 Vue 方法 API 来定义和触发 HTML 模板中的方法,并动态解析每个方法的参数。在下一个练习中,我们将探讨如何在 Vue 组件中使用 Vue 方法返回数据。

练习:返回数据的方法

Often, in a web application, we want elements to appear on the page depending on whether a condition is met or not. For instance, if our product is not in stock, our page should display the fact that it is out of stock.

在网络应用程序中,我们经常希望根据是否满足某个条件在页面上显示元素。例如,如果我们的产品没有库存,我们的页面就应该显示缺货的事实。

So, let’s figure out how we conditionally render these elements depending on whether our product is in stock or not.

因此,让我们弄清楚如何根据产品是否有库存来有条件地呈现这些元素。

Create a new Vue component file named Exercise1-09.vue in the src/components directory.

在 src/components 目录中新建一个名为 Exercise1-09.vue 的 Vue 组件文件。

修改App.vue,引入该组件并渲染:

import Exercise from "./components/Exercise1-09.vue";

Inside Exercise1-09.vue, within the section, we set up two data objects, totalItems and totalCost, which will be updated when a user clicks on our shop’s buttons:

在 Exercise1-09.vue 的 部分,我们设置了两个数据对象:totalItems 和 totalCost,当用户点击商店按钮时,这两个数据对象将被更新:

export default {

data() {

return {

totalCost: 0,

totalItems: 0

}

}

}

In the template section, we display the value of totalItems and totalCost accordingly:

在模板部分,我们会相应地显示 totalItems 和 totalCost 的值:

Returning Methods

Cart({{ totalItems }}) {{ totalCost }}

Within the script section, let’s create an addToCart method, which will update totalCost and totalItems for the current component based on the received number, n, by using this.totalCost and this.totalItems:

让我们在脚本部分创建一个 addToCart 方法,该方法将根据收到的数字 n,使用 this.totalCost 和 this.totalItems 更新当前组件的 totalCost 和 totalItems:

export default {

data() {

return {

totalCost: 0,

totalItems: 0

}

},

methods: {

addToCart(n) {

this.totalItems = this.totalItems + 1

this.totalCost = this.totalCost + n

},

},

}

Let’s iterate through a random amount to create buttons for adding a quantity to the cart. The quantity is the button’s index. Then, we bind the addToCart method to each button, with its index as the function’s input argument:

让我们遍历一个随机的数量,创建向购物车添加数量的按钮。数量就是按钮的索引。然后,我们将 addToCart 方法绑定到每个按钮,并将其索引作为函数的输入参数:

Returning Methods

Cart({{ totalItems }}) {{ totalCost }}

Add {{ n }}

Add a 10px margin to the button element for readability:

为按钮元素添加 10px 边距,以提高可读性:

button {

margin: 10px;

}

When you click on the buttons, the totalItems counter should increment by 1, but totalCost will increment by the n value, which should demonstrate a normal cart functionality.

点击按钮后,totalItems 计数器会以 1 为单位递增,但 totalCost 会以 n 为单位递增,这应该是购物车的正常功能。

Now, let’s format totalCost. Create a method called formatCurrency, which accepts one argument. We will return the same value after giving it two decimal points and a $ symbol:

现在,让我们来格式化 totalCost。创建一个名为 formatCurrency 的方法,该方法接受一个参数。在赋予两个小数点和一个 $ 符号后,我们将返回相同的值:

export default {

data() {

return {

totalCost: 0,

totalItems: 0

}

},

methods: {

addToCart(n) {

this.totalItems = this.totalItems + 1

this.totalCost = this.totalCost + n

},

// 新加的方法

formatCurrency(val) {

return `$${val.toFixed(2)}`

},

},

}

To use this method in the template, add it to the interpolated curly braces and pass the value that was there as an argument inside the method instead:

要在模板中使用该方法,请将其添加到内插的大括号中,然后将该方法中的值作为参数传递给模板:

Returning Methods

Cart({{ totalItems }}) {{ formatCurrency(totalCost) }}

Add {{ formatCurrency(n) }}

In this exercise, we were able to utilize Vue’s methods API to parse arguments into methods, return modified values, and use methods to update the local data state in a life-like scenario.

在这个练习中,我们能够利用 Vue 的方法 API 将参数解析为方法,返回修改后的值,并在一个类似生活的场景中使用方法更新本地数据状态。

In the next section, we will explore a significant part of a component – the lifecycle and available component hooks in Vue.

在下一节中,我们将探讨组件的一个重要部分--生命周期和 Vue 中可用的组件钩子。

  • 发表于:
  • 原文链接https://page.om.qq.com/page/OFkR5keV5ltxryy_8TbYsA3Q0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券