VUE3组合式API教程
1. 创建一个Vue 3项目
首先,确保你已经安装了Vue CLI。如果没有安装,可以使用以下命令进行安装:
npm install -g @vue/cli
然后,创建一个新的Vue 3项目:
vue create my-vue3-project
在创建过程中,选择Vue 3作为默认的预设。
2. 使用组合式API
在Vue 3中,组合式API主要通过setup
函数来使用。setup
函数在组件创建之前执行,并且返回的对象中的属性将暴露给模板和其他选项。
示例:基本用法
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'Counter',
setup() {
const count = ref(0);
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
};
</script>
在这个示例中,我们使用了ref
来创建一个响应式的count
变量,并在setup
函数中定义了一个increment
方法来增加count
的值。
示例:使用生命周期钩子
组合式API还允许你使用生命周期钩子。例如,使用onMounted
钩子在组件挂载时执行一些代码。
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
name: 'Counter',
setup() {
const count = ref(0);
const increment = () => {
count.value++;
};
onMounted(() => {
console.log('Component is mounted!');
});
return {
count,
increment
};
}
};
</script>
示例:使用计算属性和侦听器
组合式API还提供了computed
和watch
来处理计算属性和侦听器。
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, computed, watch } from 'vue';
export default {
name: 'Counter',
setup() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
const increment = () => {
count.value++;
};
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
return {
count,
doubleCount,
increment
};
}
};
</script>
在这个示例中,我们使用了computed
来创建一个计算属性doubleCount
,并使用watch
来监听count
的变化。
3. 总结
组合式API提供了一种更灵活和强大的方式来组织Vue组件的逻辑。通过setup
函数,你可以更好地管理和重用代码,同时使用ref
、computed
、watch
等API来处理响应式数据和副作用。
希望这个简要教程能帮助你更好地理解和使用Vue 3的组合式API。如果你有任何问题,欢迎随时提问!