代码实现vue
创建Vue项目
使用Vue CLI快速初始化项目,确保已安装Node.js和npm/yarn:
npm install -g @vue/cli
vue create my-vue-project
cd my-vue-project
npm run serve
基础组件示例
创建单文件组件HelloWorld.vue,包含模板、脚本和样式:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="count++">Count: {{ count }}</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
count: 0
}
}
}
</script>
<style scoped>
.hello {
color: #42b983;
}
</style>
状态管理(Vuex)
安装Vuex并创建store:

npm install vuex
创建store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
路由配置(Vue Router)
安装Vue Router并配置路由:

npm install vue-router
创建router/index.js:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: () => import('../views/About.vue')
}
]
})
组合式API(Composition API)
使用Vue 3的Composition API编写组件:
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
function increment() {
count.value++
}
return {
count,
increment
}
}
}
</script>






