在 Vue 3 中,组合式 API(Composition API)提供了一种更灵活的方式来组织和复用逻辑。使用组合式 API 时,你可以通过 setup
函数来定义组件的逻辑,并使用 ref
和 reactive
等响应式系统来管理数据。
下面是一个简单的 Vue 3 组件示例,展示了如何使用组合式 API 进行插值表达式。
示例代码
假设我们有一个简单的 Vue 3 应用,包含一个计数器组件,该组件显示当前的计数值并提供增加和减少计数的功能。
1. 创建 Vue 3 项目
如果你还没有创建 Vue 3 项目,可以使用 Vue CLI 来创建:
npm install -g @vue/cli
vue create my-vue3-app
cd my-vue3-app
2. 编写组件
在 src/components
目录下创建一个名为 Counter.vue
的文件,内容如下:
<template>
<div>
<h1>计数器</h1>
<p>当前计数: {{ count }}</p>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
// 定义一个响应式的计数器
const count = ref(0);
// 定义增加计数的方法
const increment = () => {
count.value++;
};
// 定义减少计数的方法
const decrement = () => {
count.value--;
};
</script>
<style scoped>
button {
margin: 5px;
padding: 10px;
}
</style>
解释
- 模板部分 (
<template>
):
- 使用插值表达式
{{ count }}
显示当前的计数值。 - 提供两个按钮,分别调用
increment
和decrement
方法来增加和减少计数。
- 脚本部分 (
<script setup>
):
- 使用
ref
创建一个响应式的计数器count
。 - 定义
increment
和decrement
方法来操作count
的值。
- 样式部分 (
<style scoped>
):
- 添加一些基本的样式,使按钮看起来更好看。
使用组件
在 src/App.vue
中引入并使用 Counter
组件:
<template>
<div id="app">
<Counter />
</div>
</template>
<script>
import Counter from './components/Counter.vue';
export default {
name: 'App',
components: {
Counter
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
运行项目
在项目根目录下运行以下命令启动开发服务器:
npm run serve
打开浏览器访问 http://localhost:8080
,你应该能看到一个简单的计数器应用,点击按钮可以增加和减少计数值。
示例:插值表达式调用函数等