网站宝搭建网站环境,网站怎么做可以合法让别人充钱,建设网站赚钱的方法,棋牌类网站设计建设#x1f308;Don’t worry , just coding! 内耗与overthinking只会削弱你的精力#xff0c;虚度你的光阴#xff0c;每天迈出一小步#xff0c;回头时发现已经走了很远。
#x1f4d7;概念 vue2中的方式叫Options API #xff0c;vue3中叫Composition API。 Composition…
Don’t worry , just coding! 内耗与overthinking只会削弱你的精力虚度你的光阴每天迈出一小步回头时发现已经走了很远。
概念 vue2中的方式叫Options API vue3中叫Composition API。 Composition API是大势所趋但是也不代表Options API 就不好只是前端发展到一定的程度之前的Options API写法是一个痛点每次修改对应的功能需要在文件中依次找到data、methods去修改效率很低所以出现了Composition API。 Option API图解 Compostion API图解 代码结构
Options API
┌─────────────────────────┐ │ Vue Component │ ├─────────────────────────┤ │ data() │ │ ┌─────────────────────┐ │ │ │ { │ │ │ │ message: │ │ │ │ count: 0 │ │ │ │ } │ │ │ └─────────────────────┘ │ ├─────────────────────────┤ │ methods │ │ ┌─────────────────────┐ │ │ │ { │ │ │ │ increment() │ │ │ │ } │ │ │ └─────────────────────┘ │ ├─────────────────────────┤ │ computed │ │ ┌─────────────────────┐ │ │ │ { │ │ │ │ computedValue │ │ │ │ } │ │ │ └─────────────────────┘ │ └─────────────────────────┘
Composition API
┌─────────────────────────┐ │ Vue Component │ ├─────────────────────────┤ │ setup() │ │ ┌─────────────────────┐ │ │ │ const message │ │ │ │ ref(“Hello, Vue!”)││ │ └─────────────────────┘ │ │ ┌─────────────────────┐ │ │ │ const count │ │ │ │ ref(0) │ │ │ └─────────────────────┘ │ │ ┌─────────────────────┐ │ │ │ const increment │ │ │ │ () { │ │ │ │ count.value; │ │ │ │ } │ │ │ └─────────────────────┘ │ ├─────────────────────────┤ │ return │ │ ┌─────────────────────┐ │ │ │ { │ │ │ │ message, │ │ │ │ increment │ │ │ │ } │ │ │ └─────────────────────┘ │ └─────────────────────────┘
理解
只要看到data、methods、computed就是vue2的写法只要看到setup就是vue3的写法项目里有人可能会2种方法混用别慌看到哪个关键字就按照哪个逻辑分析非特殊情况不要写vue2的代码了迟早要被过度到vue3
Composition API 和 Options API 的区别
定义方式
Options API: 使用对象选项定义组件的各个部分。 Composition API: 使用函数来组织逻辑更加灵活。
逻辑组织
Options API: 逻辑通常分散在 data, methods, computed 等选项中。 Composition API: 逻辑可以集中在一个函数中便于复用和维护。
示例对比
Options API 示例
templatedivh1{{ message }}/h1button clickincrement增加/button/div
/templatescript
export default {data() {return {message: Hello, Vue!,count: 0,};},methods: {increment() {this.count;this.message 你点击了 ${this.count} 次;},},
};
/script
Composition API 示例
templatedivh1{{ message }}/h1button clickincrement增加/button/div
/templatescript
import { ref } from vue;export default {setup() {const message ref(Hello, Vue!);const count ref(0);const increment () {count.value;message.value 你点击了 ${count.value} 次;};return {message,increment,};},
};
/script
关键区别总结
数据定义:
Options API: 使用 data() 返回一个对象。 Composition API: 使用 ref() 或 reactive() 来定义响应式数据。
方法定义:
Options API: 在 methods 中定义。 Composition API: 直接在 setup() 函数中定义。
逻辑复用:
Options API: 使用 mixins。 Composition API: 使用组合函数composable functions实现逻辑复用 Tips小知识点
要注意在vue3种setup函数必须把需要用到的方法、数据都return出去不然无法使用vue2中的this关键字在vue3中不支持setup无法访问到option api写法data、method中的数据和方法不向前兼容原理上来说setup执行在beforeEach之前option api的method和data中可以访问到setup定义的数据
无人扶我青云志我自踏雪至山巅。