Vue3-OptionsAPI 与 CompositionAPI以及setup概述
课程:【尚硅谷Vue3入门到实战,最新版vue3+TypeScript前端开发教程】 https://www.bilibili.com/video/BV1Za4y1r7KE/?p=6&share_source=copy_web&vd_source=63c6218111021d177660d3bec318e593
1.Api区别
vue2中弊端:
配置式api
所有功能被拆散了,每次修改一个功能需要去每一个里面寻找
vue3:组合式
将所有项组合起来
2.setup概述
vue2写法
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<!-- <button @click="showTel">查看联系方式</button>
<button @click="changename">修改名字</button>
<button @click="changeage">修改年龄</button> -->
</div>
</template>
<script lang="ts">
export default{
name:'Person',//组件名
data() {
return {
name: 'xst',
age: 18,
tel: '18837552786'
}
},
methods:
{
showTel()
{
alert(this.tel)
},
changename()
{
this.name='cuz'
},
changeage()
{
this.age+=1
},
}
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
vue3写法:
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button class="button" @click="showTel">查看联系方式</button>
<button class="button" @click="changename">修改名字</button>
<button class="button" @click="changeage">修改年龄</button>
</div>
</template>
<script lang="ts">
export default{
name:'Person',//组件名
setup()
{
let name='xst'//非响应式
let age='18'
let tel='5201314'
function showTel()
{
alert(tel)
}
function changename()
{
name='cuz'
console.log(name)
}
function changeage()
{
age+=1
console.log();
}
return{name,age,tel,showTel,changename,changeage}}
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
.button {
margin: 0 10px; /* 上下间距 0,左右各 8px 间距,可调整数值 */
}
</style>