Vue3中使用匿名函数的方法实现
作者:Python私教
Lambda函数,也称为匿名函数,是Vue3中的一种函数类型,绑定匿名方法和绑定普通方法主要是写法上的区别,其他的区别并不是很大,本文主要介绍了Vue3中使用匿名函数的方法实现,感兴趣的可以了解一下
概述
绑定匿名方法和绑定普通方法主要是写法上的区别,其他的区别并不是很大。
就拿上一个案例来说,我们使用匿名函数可以很简单的重写。
基本用法
我们创建src/components/Demo24.vue,在这个组件中,我们要:
- 1:定义count,表示用户点击的次数
- 2:用户每点击一次按钮,count的次数增加
- 3:如果用户点击超过100次,我们提示“看样子你真的很喜欢这篇文章的嘞”
- 4:如果用户点击超过1000次,我们提示“作者有你这样的粉丝真实太好了嘞”
代码如下:
<script setup>
import {ref} from "vue";
const count = ref(0)
const onClick = () => {
count.value++
if (count.value === 100) {
alert("看样子你真的很喜欢这篇文章的嘞")
} else if (count.value === 1000) {
alert("作者有你这样的粉丝真实太好了嘞")
}
}
</script>
<template>
<div>
<h3>当前点击次数:{{ count }}</h3>
<button @click="onClick">点击</button>
</div>
</template>
<style>
span {
margin: 15px;
}
</style>
接着,我们修改src/App.vue,引入Demo24.vue并进行渲染:
<script setup> import Demo from "./components/Demo24.vue" </script> <template> <h1>欢迎跟着Python私教一起学习Vue3入门课程</h1> <hr> <Demo/> </template>
然后,我们浏览器访问:http://localhost:5173/

代码分析
修改之前的方法:
function onClick(){
count.value++
if (count.value===100){
alert("看样子你真的很喜欢这篇文章的嘞")
}else if (count.value===1000){
alert("作者有你这样的粉丝真实太好了嘞")
}
}
修改之后的方法:
function onClick(){
count.value++
if (count.value===100){
alert("看样子你真的很喜欢这篇文章的嘞")
}else if (count.value===1000){
alert("作者有你这样的粉丝真实太好了嘞")
}
}
完整代码
package.json
{
"name": "hello",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.3.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"vite": "^5.0.0"
}
}
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" rel="external nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
src/App.vue
<script setup> import Demo from "./components/Demo24.vue" </script> <template> <h1>欢迎跟着Python私教一起学习Vue3入门课程</h1> <hr> <Demo/> </template>
src/components/Demo24.vue
<script setup>
import {ref} from "vue";
const count = ref(0)
function onClick(){
count.value++
if (count.value===100){
alert("看样子你真的很喜欢这篇文章的嘞")
}else if (count.value===1000){
alert("作者有你这样的粉丝真实太好了嘞")
}
}
</script>
<template>
<div>
<h3>当前点击次数:{{count}}</h3>
<button @click="onClick">点击</button>
</div>
</template>
<style>
span{
margin: 15px;
}
</style>
启动方式
yarn yarn dev
浏览器访问:http://localhost:5173/
到此这篇关于Vue3中使用匿名函数的方法实现的文章就介绍到这了,更多相关Vue3 匿名函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
