创建Vue项目
使用Vue CLI快速创建项目,确保已安装Node.js和npm。运行以下命令生成新项目:
vue create my-vue-project
选择默认配置或手动配置(如Babel、Router、Vuex等)。
组件开发
单文件组件(.vue)包含模板、脚本和样式三部分。以下是一个计数器组件示例:
<template>
<div>
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
}
</script>
<style scoped>
button {
margin: 0 10px;
}
</style>
路由配置
在src/router/index.js中定义路由规则:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
状态管理(Vuex)
创建store管理全局状态。示例store模块:
import { createStore } from 'vuex'
export default createStore({
state: {
user: null
},
mutations: {
SET_USER(state, user) {
state.user = user
}
},
actions: {
login({ commit }, user) {
commit('SET_USER', user)
}
},
getters: {
isAuthenticated: state => !!state.user
}
})
API调用
使用axios进行HTTP请求。创建src/api目录存放API模块:
import axios from 'axios'
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
})
export const getPosts = () => api.get('/posts')
export const createPost = (data) => api.post('/posts', data)
表单验证
使用Vuelidate进行表单验证:
<template>
<form @submit.prevent="submit">
<input v-model="email" @blur="$v.email.$touch()">
<span v-if="$v.email.$error">请输入有效邮箱</span>
<button type="submit">提交</button>
</form>
</template>
<script>
import { required, email } from 'vuelidate/lib/validators'
export default {
data() {
return {
email: ''
}
},
validations: {
email: { required, email }
},
methods: {
submit() {
this.$v.$touch()
if (!this.$v.$invalid) {
// 提交逻辑
}
}
}
}
</script>
响应式布局
使用CSS Grid或Flexbox实现响应式布局:
<template>
<div class="container">
<header>Header</header>
<main>Main Content</main>
<aside>Sidebar</aside>
<footer>Footer</footer>
</div>
</template>
<style>
.container {
display: grid;
grid-template-columns: 1fr 3fr;
grid-gap: 20px;
}
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
}
</style>
测试组件
使用Jest测试Vue组件:
import { mount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'
describe('Counter.vue', () => {
it('increments count when button is clicked', () => {
const wrapper = mount(Counter)
wrapper.find('button:nth-child(2)').trigger('click')
expect(wrapper.vm.count).toBe(1)
})
})
4万+

被折叠的 条评论
为什么被折叠?



