08 在Vue3中使用方法

2023-12-17 08:29:27

概述

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 实例,该实例表示组件的实例:

<script>
export default {
  methods: {
    myMethod() { console.log('my first method'); }
  }
}
</script>

From Vue 3.0 onward, with <script setup>, 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 开始,使用 <script setup>,就像使用本地数据一样,可以将方法定义为普通函数,其工作方式与传统方法相同。因此,我们可以将前面的代码重写如下:

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

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,如以下代码块所示:

<template>
  <button id="click-me" v-on:click="myMethod">Click me</button>
  <button id="click-me" @click="myMethod">Click me shorter</button>
</template>

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,引入该组件并渲染:

<script setup>
import Exercise from "./components/Exercise1-08.vue";
</script>
<template>
  <Exercise/>
</template>

Inside Exercise1-08.vue, within the <script setup> 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 的 <script setup> 部分,让我们定义一个方法 triggerAlert,该方法接收一个索引并显示一个提示,告知用户点击了哪个索引:

<script setup>
const triggerAlert = (index) => {
  alert(`${index} has been clicked`)
}
</script>

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 次,并将索引值显示为每个按钮的标签:

<template>
  <div>
    <h1>Triggering Vue Methods</h1>
    <ul>
      <li v-for="index in 5" :key="index">
        <button>Trigger {{ index }}</button>
      </li>
    </ul>
  </div>
</template>

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

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

<template>
  <div>
    <h1>Triggering Vue Methods</h1>
    <ul>
      <li v-for="index in 5" :key="index">
        <button @click="triggerAlert(index)">
          Trigger {{ index }}
        </button>
      </li>
    </ul>
  </div>
</template>

Add a margin between each button for readability:

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

<style>
button {
  margin: 10px;
}
</style>

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,引入该组件并渲染:

<script setup>
import Exercise from "./components/Exercise1-09.vue";
</script>
<template>
  <Exercise/>
</template>

Inside Exercise1-09.vue, within the <script> 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 的 <script> 部分,我们设置了两个数据对象:totalItems 和 totalCost,当用户点击商店按钮时,这两个数据对象将被更新:

<script>
export default {
  data() {
    return {
      totalCost: 0,
      totalItems: 0
    }
  }
}
</script>

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

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

<template>
  <div>
    <h1>Returning Methods</h1>
    <div>Cart({{ totalItems }}) {{ totalCost }}</div>
  </div>
</template>

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:

<script>
export default {
  data() {
    return {
      totalCost: 0,
      totalItems: 0
    }
  },
  methods: {
    addToCart(n) {
      this.totalItems = this.totalItems + 1
      this.totalCost = this.totalCost + n
    },
  },
}
</script>

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 方法绑定到每个按钮,并将其索引作为函数的输入参数:

<template>
  <div>
    <h1>Returning Methods</h1>
    <div>Cart({{ totalItems }}) {{ totalCost }}</div>
    <ul>
      <li v-for="n in 5" :key="n">
        <button @click="addToCart(n)">Add {{ n }}
        </button>
      </li>
    </ul>
  </div>
</template>

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

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

<style>
button {
  margin: 10px;
}
</style>

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 的方法,该方法接受一个参数。在赋予两个小数点和一个 $ 符号后,我们将返回相同的值:

<script>
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)}`
    },
  },
}
</script>

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:

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

<template>
  <div>
    <h1>Returning Methods</h1>
    <div>Cart({{ totalItems }}) {{ formatCurrency(totalCost) }}</div>
    <ul>
      <li v-for="n in 5" :key="n">
        <button @click="addToCart(n)">Add {{ formatCurrency(n) }}</button>
      </li>
    </ul>
  </div>
</template>

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://blog.csdn.net/qq_37703224/article/details/135040030
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。