概述
使用点击事件绑定一个普通方法是我个人在真实开发中比较喜欢用的一种操作,原因是我认为使用function关键字标识出来的方法,在大段的代码中,看起来更有识别性,能够很轻松的和const定义的常量区分开来。
虽然使用const也可以通过匿名函数来定义方法,而且比较新颖,但是我目前并不推荐这种做法,因为我并没发现const定义的函数比function定义的函数有哪些非常明显的优势,甚至会让代码的可读性变低。
这里,我们演示一下事件绑定普通方法,以一个非常经典的计数器案例为例子。
基本用法
我们创建src/components/Demo23.vue,在这个组件中,我们要:
- 1:定义count,表示用户点击的次数
- 2:用户每点击一次按钮,count的次数增加
- 3:如果用户点击超过100次,我们提示“看样子你真的很喜欢这篇文章的嘞”
- 4:如果用户点击超过1000次,我们提示“作者有你这样的粉丝真实太好了嘞”
代码如下:
<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>
接着,我们修改src/App.vue,引入Demo23.vue并进行渲染:
<script setup>
import Demo from "./components/Demo23.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
然后,我们浏览器访问:http://localhost:5173/
完整代码
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" />
<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/Demo23.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
src/components/Demo23.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/