vue实现index dem
Vue 实现 Index Demo
使用 Vue 实现一个简单的 Index Demo 可以通过以下步骤完成。以下示例基于 Vue 3 的 Composition API。
创建 Vue 项目
使用 Vue CLI 或 Vite 创建一个新的 Vue 项目。以下是使用 Vite 的示例:
npm create vite@latest vue-index-demo --template vue
cd vue-index-demo
npm install
npm run dev
修改 App.vue
在 src/App.vue 中,编写一个简单的 Index 页面:
<template>
<div class="index-demo">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
<button @click="increment">点击计数: {{ count }}</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const title = ref('Vue Index Demo');
const description = ref('这是一个简单的 Vue Index 页面示例。');
const count = ref(0);
const increment = () => {
count.value++;
};
</script>
<style scoped>
.index-demo {
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
background-color: #42b983;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
运行项目
启动开发服务器:
npm run dev
打开浏览器访问 http://localhost:3000,即可看到 Index Demo 页面。
添加路由(可选)
如果需要多页面导航,可以安装 Vue Router:

npm install vue-router@4
创建路由配置文件 src/router/index.js:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
在 src/main.js 中引入路由:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
创建 src/views/Home.vue 文件,内容与之前的 App.vue 类似。

使用状态管理(可选)
如果需要全局状态管理,可以安装 Pinia:
npm install pinia
在 src/main.js 中引入 Pinia:
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia());
app.mount('#app');
创建一个 store 文件 src/stores/counter.js:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
在组件中使用:
<script setup>
import { useCounterStore } from '../stores/counter';
const counter = useCounterStore();
</script>
<template>
<button @click="counter.increment">点击计数: {{ counter.count }}</button>
</template>
通过以上步骤,可以快速实现一个 Vue Index Demo,并根据需求扩展功能。






