vue3.0项目创建好之后,来看看一个简单组件内的代码顺便介绍几个特点:
1.组合式api就是指把vue2.0中的data,computed,methods,watch都集中在3.0中的setup()中
2.setup取代beforeCreate,created这两个周期,也就是原本放在这两个钩子的内容现在放在setup中
3.在setup里无法再使用this,因为在执行setup的时候组件实例还没创建成功(setup执行在beforeCreate之前)。
4.接收两个参数props,context(具体的后面讲)
5.代码可读性更高,维护也更方便。当然也完美兼容vue2.x
<template><divclass="home">{{user.name}}--{{user.age}}--{{num}}--{{doubleCount}}<button @click="change"></button></div></template><script>import{ ref, reactive, computed, watch} from'vue'export default{ name:'Home',setup(){ const user= reactive({ name:'jerry', age:18}) // 创建引用类型数据使用reactive const num= ref(6) // 创建基础数据类型使用ref,使用是用.vulue const doubleCount= computed(()=>{return num.value *2}) // watch的单个值写法,第一个参数是一个getter函数,该函数返回一个响应式对象,要响应式。 watch(()=> num.value,(newValue, old)=>{ // newValue新值,old旧值 console.log(newValue, old,'--w')}) // watch的多个值写法 /* const num1= ref(11) watch([count, count1],([newCount, newCount2],[oldCount, oldCount2])=>{ console.log([newCount, newCount2],'--',[oldCount, oldCount2],'--w')}) watch(()=> user,(newValue, oldValue)=>{ console.log(newValue, oldValue)},{ deep:true}) // 深入监听user对象内部变化 watch([count, count1],(newValue, oldValue)=>{ console.log(newValue)//[newCount, newCount2] console.log(oldValue)//[oldCount, oldCount2]}) */ const change=()=>{ num.value++}return{ user, num, doubleCount, change}},created(){ // vue2.0的内容也还是可以照常用的}}</script>
setup()的两个参数
<script>import{ toRefs, toRef} from'vue'export default{ name:'Home', // 因为props是响应性的,使用解构后会消除其响应性,所以需要使用toRefs, toRef // 但是context不具有响应性,可以直接使用解构赋值,但是只能访问attrs, slots, emit, expose setup(props, context){ const{ name}= toRefs(props) const{ name0}= toRef(props,'jerry') // toRef的第二个参数就类似于函数形参的默认值 const{attrs, slots, emit, expose}= context // 可以打印出来自己去看这几个属性return{}}}</script>
方便维护,便于理解
这样看就不会像vue2.0那样,在维护的时候想要查询某个变量的逻辑,要去data,watch,methos等等里面去找,代码一多,眼睛都给你看画,脑壳看痛
<script>import{ ref, reactive} from'vue'export default{ name:'Home', setup(props, context){ const num= ref(0) /*. .这里都是对num的操作代码. */ const user= reactive({name:'jerry'}) /*. .这里都是对user的操作代码. */return{}}}</script>
热门文章
- 免费领养宠物的平台小狗是真的吗(免费领养宠物的平台小狗是真的吗知乎)
- 12月14日|V2ray/SSR/Shadowrocket/Clash每天更新21.8M/S免费节点订阅链接,付费节点订阅推荐
- 1月13日|Clash/SSR/V2ray/Shadowrocket每天更新20.7M/S免费节点订阅链接,付费节点订阅推荐
- 如何在HTML 5中将视频添加到网站背景
- 重庆宠物领养贴吧论坛官网(重庆宠物领养重庆宠物赠送)
- 12月28日|SSR/Shadowrocket/V2ray/Clash每天更新20.9M/S免费节点订阅链接,付费节点订阅推荐
- 猫咪3针疫苗一共多少元钱一针 猫咪3针疫苗一共多少元钱一针啊
- Spring boot 注解@Async不生效 无效 不起作用
- Maven安装与配置,Idea配置Maven
- 1月8日|Shadowrocket/Clash/V2ray/SSR每天更新18.5M/S免费节点订阅链接,付费节点订阅推荐