当前位置: 首页 > news >正文

vue组合式和选项式

Vue中的组合式(Composition API)和选项式(Options API)是两种不同的编写组件逻辑的方法。

组合式API(Composition API):

  • 使用函数来定义组件逻辑,可以更灵活地重用和组合逻辑。
  • 使用setup函数作为组件的入口点,在这里可以访问props,attrs,slots和emit。
  • 使用ref和reactive来管理响应式状态。
  • 使用computed和watch来定义计算属性和观察者。

选项式API(Options API):

  • 使用data函数返回响应式数据。
  • 使用computed选项定义计算属性。
  • 使用watch选项来观察响应式数据的变化。
  • 使用methods定义组件的方法。
  • 使用components选项注册局部组件。

组合式API,代码示例:

import { ref, reactive, computed, watch, onMounted } from 'vue';export default {setup(props, { attrs, slots, emit }) {const count = ref(0);const state = reactive({ message: 'Hello Vue!' });const doubleCount = computed(() => count.value * 2);watch(count, (newValue, oldValue) => {console.log(`The new count is ${newValue}`);});onMounted(() => {console.log('Component is mounted!');});function increment() {count.value++;}return { count, state, doubleCount, increment };}
};

选项式API,代码示例:

export default {data() {return {count: 0,message: 'Hello Vue!'};},computed: {doubleCount() {return this.count * 2;}},watch: {count(newValue, oldValue) {console.log(`The new count is ${newValue}`);}},mounted() {console.log('Component is mounted!');},methods: {increment() {this.count++;}}
};

两种方法各有优缺点,组合式API通过函数组合提供更多灵活性,而选项式API则更为简单和直观。Vue 3中推荐使用组合式API来编写组件逻辑。

http://www.lryc.cn/news/361727.html

相关文章:

  • 使用OpenCV创建全景图像
  • Nios II 实现流水灯实验
  • Spring boot 随笔 1 DatasourceInitializer
  • vue3_组件间通信方式
  • mysql的锁(全局锁)
  • Spring Boot 整合开源 Tess4J库 实现OCR图片文字识别
  • 使用 Docker 和 Docker Compose 部署 Vue
  • 力扣linkedlist
  • springboot 启动原理、启动过程、启动机制的介绍
  • 大模型ChatGLM的部署与微调
  • 全球七家半导体工厂建设受阻:英特尔、三星、台积电等面临延期挑战
  • JavaScript错误;调试;“=”,“==”,“===”的区别
  • thinkphp6的请求
  • ant design vue 表格错位,表头错位
  • 【小白向】微信小程序解密反编译教程
  • Flutter基础 -- Dart 语言 -- 类抽象接口继承函数库
  • 【TB作品】msp430单片机,播放蜂鸣器音乐,天空之城
  • C语言(数据存储)
  • Linux shell编程学习笔记56:date命令——显示或设置系统时间与日期
  • Realsense的一些事情
  • CISCN 2023 初赛 被加密的生产流量
  • 初识C语言第三十天——设计三子棋游戏
  • ehcache3多级缓存应用
  • C# WinForm —— 24 Threading.Timer 组件介绍与使用
  • 03-07Java自动化之JAVA基础之循环
  • 【人工智能Ⅱ】实验8:生成对抗网络
  • vmware将物理机|虚拟机转化为vmware虚机
  • redis 高可用及哨兵模式 @by_TWJ
  • 封装tab栏,tab切换可刷新页面
  • JavaScript第八讲:日期,Math,自定义对象