绑定匿名方法和绑定普通方法主要是写法上的区别,其他的区别并不是很大。
就拿上一个案例来说,我们使用匿名函数可以很简单的重写。
我们创建src/components/Demo24.vue,在这个组件中,我们要:
代码如下:
<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("作者有你这样的粉丝真实太好了嘞")
}
}
{
"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"
}
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
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 + Vuetitle>
head>
<body>
<div id="app">div>
<script type="module" src="/src/main.js">script>
body>
html>
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<script setup>
import Demo from "./components/Demo24.vue"
script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程h1>
<hr>
<Demo/>
template>
<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/