Vue3 中的setup
1.因setup处于beforeCreate和Created之间,导致在setup无法使用data与method中的数据与方法
2.setup函数是 Composition API(组合API)的入口
3.在setup中定义的变量以及方法最后都需要return回去
使用案例:
<template> <div> <h1>setup 函数</h1> <h1>名称:{{name}}</h1> <h1>年龄:{{age}}</h1> <h1>性别:{{sex}}</h1> </div> </template> <script> export default { setup() { const name = '我是𝒆𝒅.' // 定义一个基本类型变量 const age = 10 const sex = true return { name, age, sex } } } </script>
<template> <div> <h1>setup 函数</h1> <h1>名称:{{name}}</h1> <h1>年龄:{{age}}</h1> <h1>性别:{{sex}}</h1> </div> </template> <script> export default { setup() { const name = '我是𝒆𝒅.' // 定义一个基本类型变量 const age = 10 const sex = true return { name, age, sex } } } </script>
<template> <div> <h1>setup 函数</h1> <h1>名称:{{boy.name}}</h1> <h1>年龄:{{boy.age}}</h1> <h1>性别:{{boy.sex}}</h1> <p v-for="(item, index) in todo" :key="index">{{item}}</p> </div> </template> <script> export default { setup() { const boy = { name: '我是𝒆𝒅.', age: 10, sex: true } const todo = ['弹吉他', '做作业', '练街舞'] return { boy, todo } } } </script>
创建方法两种办法:
// 一、通过 function 的方式创建
function btn() {
console.log('按钮被点击了')
}
// 二、通过箭头函数的方式创建
const btn = () => {
console.log('按钮被点击了')
}
必须将方法返回出去才能使用:
<template> <div> <h1>setup 函数</h1> <el-button type="primary" @click="btn">按钮</el-button> </div> </template> <script> export default { setup() { // 通过箭头函数的方式创建 const btn = () => { console.log('按钮被点击了') } return { btn } // 将时间抛出 } } </script>
(转载:https://blog.csdn.net/qq_60633836/article/details/123537207)