vue3.0的写法
一、setup的特性
1、setup函数是处于生命周期函数beforeCreate 和 Created两个钩子函数之间的函数, Vue 直接将 setup函数中的this修改成了 undefined, 所以setup函数里没有了this,访问他们变成以下形式: this.xxx=》context.xxx
2、setup函数是 Composition API(组合API)的入口
3、在setup函数中定义的变量和方法最后都是需要 return 出去的 不然无法再模板中使用
4、setup函数只能是同步的不能是异步的
二、vue2.0与vue3.0用法的区别
vue2.0:需要在 props 里面设置接收参数,在 data 里面设置变量,在 computed 里面设置计算属性,在 watch 里面设置监听属性,在methods 里面设置事件方法
而在vue3.0中:我们可以直接写在 setup 里面
三、setup用法
setup函数提供了两个参数 props和context,setup函数里没有了this,在 vue3.0 中,访问他们变成以下形式: this.xxx=》context.xxx
第一个参数props: props是一个对象,包含父组件传递给子组件的所有数据。在子组件中使用props进行接收。包含配置声明并传入的所有的属性的对象,也就是说:如果你想通过props的方式输出父组件传递给子组件的值。你需要使用props进行接收配置。即props:{…},如果你未通过Props进行接受配置,则输出的值是undefined。
具体用法:
<template>
<div id="app">
{{name}}
<p>{{age}}</p>
<button @click="plusOne()">+</button>
</div>
</template>
<script>
import {ref, onMounted} from 'vue'
export default {
name:'app',
setup(props, context) {
//接受子组件传来的参数
let taskId= ref("");
taskId.value = props.id
//定义变量
const name =ref('小四')
const age=ref(18)
const plusOne= () => {
age.value++ //想改变值或获取值 必须.value
}
const getDetail = () => {
console.log("进入页面调用方法")
}
//进入页面调用
onMounted(() => {
getDetail ()
})
return { //必须返回 模板中才能使用
name,
age,
plusOne
}
},
props: { //接收子组件传值
id: Number | String,
},
components: {},
}
</script>