vue项目操作如何实现
Vue 项目基本操作实现
创建 Vue 项目
使用 Vue CLI 快速创建项目:
npm install -g @vue/cli
vue create project-name
cd project-name
npm run serve
组件定义与使用
单文件组件结构(.vue 文件):
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
div {
color: red;
}
</style>
数据绑定
双向数据绑定使用 v-model:
<input v-model="inputText">
<p>{{ inputText }}</p>
条件渲染
v-if 和 v-show 控制元素显示:
<div v-if="isVisible">显示内容</div>
<div v-show="isActive">切换显示</div>
列表渲染
v-for 渲染数组或对象:
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
</li>
事件处理
v-on 或 @ 绑定事件:
<button @click="handleClick">点击</button>
组件通信
父传子通过 props:
<!-- 父组件 -->
<child-component :message="parentMsg"></child-component>
<!-- 子组件 -->
<script>
export default {
props: ['message']
}
</script>
子传父通过 $emit:
<!-- 子组件 -->
<button @click="$emit('custom-event', data)">触发</button>
<!-- 父组件 -->
<child-component @custom-event="handleEvent"></child-component>
状态管理(Vuex)
store 基本结构:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
组件中使用:
this.$store.commit('increment')
this.$store.dispatch('incrementAsync')
路由配置(Vue Router)
基本路由设置:
// router.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')
}
]
})
导航使用:
<router-link to="/">Home</router-link>
<router-link :to="{ name: 'about' }">About</router-link>
API 请求
使用 axios 示例:
import axios from 'axios'
axios.get('/api/data')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error(error)
})
生命周期钩子
常用生命周期示例:
export default {
created() {
// 实例创建后调用
},
mounted() {
// DOM 挂载后调用
},
updated() {
// 数据更新后调用
},
destroyed() {
// 实例销毁前调用
}
}
自定义指令
全局指令注册:
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
使用指令:
<input v-focus>
混入 (Mixins)
定义混入对象:
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
组件中使用:
export default {
mixins: [myMixin]
}
插件开发
简单插件示例:
const MyPlugin = {
install(Vue) {
Vue.prototype.$myMethod = function () {
console.log('Plugin method')
}
}
}
Vue.use(MyPlugin)
过渡动画
CSS 过渡示例:
<transition name="fade">
<p v-if="show">过渡内容</p>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
服务端渲染 (SSR)
使用 Nuxt.js 创建 SSR 应用:
npx create-nuxt-app project-name






