vue组合式和选项式

简介: 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++;
}
}
};

相关文章
|
1天前
|
JavaScript 前端开发 API
|
1天前
|
JavaScript 前端开发 网络架构
Vue如何实现页面跳转路由,实现单页面跳转
Vue如何实现页面跳转路由,实现单页面跳转
|
1天前
|
JavaScript
|
1天前
|
JavaScript 前端开发
Vue,如何引入样式文件
Vue,如何引入样式文件
|
1天前
|
JavaScript
|
1天前
|
JavaScript
Vue搭配ELEMENT之后,右侧点击栏点击跳转到空白页解决方法
Vue搭配ELEMENT之后,右侧点击栏点击跳转到空白页解决方法
|
1天前
|
JavaScript
vue : 无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保 路径正确,然后再试一次。
vue : 无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保 路径正确,然后再试一次。
|
1天前
|
JavaScript
|
1天前
|
JavaScript 前端开发
|
1天前
|
JavaScript 前端开发 网络架构
技术笔记:vue——介绍和使用
技术笔记:vue——介绍和使用