setup概述
setup
是Vue3
中新的配置项,值是一个函数,组件中所用到的数据、方法、计算属性、监视
等等,均配置在setup中。
- setup函数返回的对象中的内容,可直接在模版中使用。
- setup中不能使用
this
关键字,this
是undefined
。 - setup会在
beforeCreate()
函数之前调用,领先所有的钩子函数
执行的。
写法一(用于理解,不推荐这种写法)
代码
<template>
<div>
<h2> 数字:{{ n }} </h2>
<button @click="alertInformation">显示信息</button>
</div>
</template>
<script lang='ts'>
export default {
name: "App",
setup() {
//定义变量和方法
let n: number = 10;
function alertInformation() {
alert("Hello World!");
}
//需要返回,才能在模板中使用
return { n, alertInformation }
}
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
</style>
运行结果
注意:此时定义的变量n不是响应式的,更改n不会在页面渲染。
数字没有重新渲染到页面
代码
<template>
<div>
<h2> 数字:{{ n }} </h2>
<button @click="alertInformation">显示信息</button>
<button @click="changeN">n加1</button>
</div>
<div>
</div>
</template>
<script lang='ts'>
export default {
name: "App",
setup() {
//定义变量和方法
let n: number = 10;
function alertInformation() {
alert("Hello World!");
}
//测试
function changeN() {
n++;
console.log("数字n", n)
}
//需要返回,才能在模板中使用
return { n, alertInformation, changeN }
}
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
</style>
运行结果
写法二(推荐写法)
使用setup语法糖
在script标签上添加setup
插件名:Vue-Official
代码
<template>
<div>
<h2> {{ n }} </h2>
<button @click="alertInformation">显示信息</button>
</div>
</template>
<!--Vue 3 setup语法糖 -->
<script setup lang='ts' name="App">
let n = 10;
function alertInformation() {
alert("Hello world!");
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
</style>
注意:此时变量n也不是响应式。
需要了解响应式,查看官方文档或者文章Vue3-ref和reactive
小提示:.value,可以通过Vue-Official插件自动生成。
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容