代码量:200行以上
博客量:1
时间:2h
- vue2中的data和methods可以与setup并列写,但是:
- data和methods可以利用this调用setup中的数据
- 而,setup中,不能调用data和methods中的数据
<!--Person.vue-->
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">查看联系方式</button>
</div>
</template>
<script lang='ts'>
export default{
name:'Person',
setup(){
//数据部分
let name = '张三'
let age = 18
let tel = '13383619197'
//函数部分
function changeName(){
name = 'zhang-san'
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
return {name,age,changeName,changeAge,showTel}
//return ()=> '哈哈' setup也可以返回一个渲染函数
}
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding:20px;
}
button{
margin: 0 5px;
}
</style>
setup的语法糖
<!--常用方式-->
<script lang='ts'>
export default{
name:'Person',
setup(){
let a = 666
return {a}
}
}
</script>
<!--简便用法-->
<script lang='ts'>
export default{
name:'Person',
}
</script>
<script lang='ts' setup>
let a = 666
</script>
<!--安装插件后还可以简化-->
npm i vite-plugin-vue-setup-extend -D
<!--然后在vite.config.ts引入-->
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
VueSetupExtend(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
<!--可简化为:-->
<script lang='ts' setup name='Person234'>
let a = 666
</script>
- 修改后的Person.vue
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">查看联系方式</button>
</div>
</template>
<script lang="ts" name="Person234" setup>
//数据部分
let name = '张三'
let age = 18
let tel = '13383619197'
//函数部分
function changeName(){
name = 'zhang-san'
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding:20px;
}
button{
margin: 0 5px;
}
</style>
标签:function,vue,name,--,age,let,vue3,setup
From: https://www.cnblogs.com/muzhaodi/p/18194531