vue实现网站代码
Vue 实现网站代码指南
环境搭建
确保已安装 Node.js(建议 LTS 版本) 通过 npm 或 yarn 安装 Vue CLI 工具:
npm install -g @vue/cli
# 或
yarn global add @vue/cli
创建项目
使用 Vue CLI 创建新项目:
vue create my-website
选择默认配置或手动配置(推荐选择 Babel、Router、Vuex 等常用功能)
项目结构
典型 Vue 项目目录结构:
src/
├── assets/ # 静态资源
├── components/ # 可复用组件
├── views/ # 页面级组件
├── router/ # 路由配置
├── store/ # Vuex 状态管理
├── App.vue # 根组件
└── main.js # 入口文件
基础组件示例
创建简单的按钮组件 Button.vue:
<template>
<button class="btn" @click="$emit('click')">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'MyButton'
}
</script>
<style scoped>
.btn {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
</style>
路由配置
在 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')
}
]
})
状态管理
简单的 Vuex store 示例 (store/index.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)
}
}
})
API 调用
使用 axios 进行 HTTP 请求:
import axios from 'axios'
export default {
methods: {
async fetchData() {
try {
const response = await axios.get('https://api.example.com/data')
this.data = response.data
} catch (error) {
console.error('Error fetching data:', error)
}
}
}
}
构建部署
开发模式运行:
npm run serve
生产环境构建:

npm run build
常用优化技巧
-
路由懒加载:
component: () => import('./views/About.vue') -
按需加载组件库(如 Element UI):
import { Button, Select } from 'element-ui' -
使用 Vue 插件增强功能:
import VueLazyload from 'vue-lazyload' Vue.use(VueLazyload) -
配置环境变量: 在项目根目录创建
.env文件:VUE_APP_API_URL=https://api.example.com






