您好,登录后才能下订单哦!
Vue.js 是一个流行的前端框架,它的最新版本 Vue 3 带来了许多新特性和改进。本文将详细介绍如何从零开始搭建一个 Vue 3 项目,涵盖从环境准备到项目部署的完整流程。无论你是初学者还是有一定经验的开发者,本文都将为你提供详细的指导和实用的技巧。
在开始之前,确保你的系统已经安装了 Node.js。Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时,它允许你在服务器端运行 JavaScript 代码。
node -v
npm -v
如果显示了版本号,说明安装成功。
Vue CLI 是 Vue.js 官方提供的命令行工具,用于快速搭建 Vue 项目。
npm install -g @vue/cli
vue --version
如果显示了版本号,说明安装成功。
vue create my-vue3-project
在提示中选择 Manually select features
,然后选择以下特性:
选择 Vue 3 版本。
选择 ESLint + Prettier
作为代码风格检查工具。
选择 In dedicated config files
将配置放在单独的文件中。
选择 Save this as a preset for future projects
保存配置,方便下次使用。
创建完成后,项目结构如下:
my-vue3-project/
├── node_modules/
├── public/
│ ├── favicon.ico
│ └── index.html
├── src/
│ ├── assets/
│ ├── components/
│ ├── router/
│ ├── store/
│ ├── views/
│ ├── App.vue
│ └── main.ts
├── .eslintrc.js
├── .prettierrc
├── babel.config.js
├── package.json
├── tsconfig.json
└── vue.config.js
node_modules/
:存放项目依赖的第三方库。public/
:存放静态资源,如 index.html
。src/
:存放项目源代码。
assets/
:存放静态资源,如图片、字体等。components/
:存放 Vue 组件。router/
:存放路由配置。store/
:存放 Vuex 状态管理配置。views/
:存放页面组件。App.vue
:根组件。main.ts
:项目入口文件。.eslintrc.js
:ESLint 配置文件。.prettierrc
:Prettier 配置文件。babel.config.js
:Babel 配置文件。package.json
:项目配置文件,包含项目依赖和脚本。tsconfig.json
:TypeScript 配置文件。vue.config.js
:Vue 项目配置文件。ESLint 是一个 JavaScript 代码检查工具,用于发现和修复代码中的问题。
.eslintrc.js
文件,配置如下: module.exports = {
root: true,
env: {
node: true,
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'@vue/prettier',
'@vue/prettier/@typescript-eslint',
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
};
package.json
中添加以下脚本: "scripts": {
"lint": "eslint --ext .js,.vue src"
}
npm run lint
Prettier 是一个代码格式化工具,用于统一代码风格。
.prettierrc
文件,配置如下: {
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"tabWidth": 2
}
package.json
中添加以下脚本: "scripts": {
"format": "prettier --write \"src/**/*.{js,vue,ts}\""
}
npm run format
TypeScript 是 JavaScript 的超集,提供了类型检查和更强大的面向对象编程特性。
tsconfig.json
文件,配置如下: {
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": ["webpack-env"],
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx"],
"exclude": ["node_modules"]
}
src
目录下创建 shims-vue.d.ts
文件,配置如下: declare module '*.vue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用。
npm install vue-router@4
src/router/index.ts
文件,配置如下: import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
src/main.ts
文件中引入并使用路由: import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
src/App.vue
文件中添加 <router-view>
标签: <template>
<div id="app">
<router-view />
</div>
</template>
Vuex 是 Vue.js 的官方状态管理库,用于集中管理应用的状态。
npm install vuex@next
src/store/index.ts
文件,配置如下: import { createStore } from 'vuex';
export default createStore({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment({ commit }) {
commit('increment');
},
},
modules: {},
});
src/main.ts
文件中引入并使用 Vuex: import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
createApp(App).use(router).use(store).mount('#app');
src/views/Home.vue
文件中使用 Vuex: <template>
<div class="home">
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { mapState, mapActions } from 'vuex';
export default defineComponent({
computed: {
...mapState(['count']),
},
methods: {
...mapActions(['increment']),
},
});
</script>
Element Plus 是一个基于 Vue 3 的 UI 组件库,提供了丰富的组件和样式。
npm install element-plus
src/main.ts
文件中引入并使用 Element Plus: import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
createApp(App).use(router).use(store).use(ElementPlus).mount('#app');
src/views/Home.vue
文件中使用 Element Plus 组件: <template>
<div class="home">
<el-button type="primary" @click="increment">Increment</el-button>
<h1>Count: {{ count }}</h1>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { mapState, mapActions } from 'vuex';
export default defineComponent({
computed: {
...mapState(['count']),
},
methods: {
...mapActions(['increment']),
},
});
</script>
Axios 是一个基于 Promise 的 HTTP 客户端,用于发送 HTTP 请求。
npm install axios
src
目录下创建 api
文件夹,并在其中创建 index.ts
文件: import axios from 'axios';
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
});
export default api;
src/views/Home.vue
文件中使用 Axios 发送请求: <template>
<div class="home">
<el-button type="primary" @click="fetchData">Fetch Data</el-button>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import api from '../api';
export default defineComponent({
setup() {
const posts = ref([]);
const fetchData = async () => {
const response = await api.get('/posts');
posts.value = response.data;
};
return {
posts,
fetchData,
};
},
});
</script>
代码分割是一种优化技术,用于将代码拆分成多个小块,按需加载,减少初始加载时间。
src/router/index.ts
文件中使用动态导入实现代码分割: const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
},
];
懒加载是一种优化技术,用于延迟加载非关键资源,提高页面加载速度。
src/views/About.vue
文件中使用懒加载: <template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'About',
});
</script>
v-if
和 v-show
控制组件的渲染和显示。keep-alive
缓存组件状态。v-once
渲染静态内容。v-memo
优化列表渲染。 npm run build
dist
目录下。dist
目录下的文件上传到服务器。index.html
文件。本文详细介绍了如何从零开始搭建一个 Vue 3 项目,涵盖了环境准备、项目创建、配置、路由、状态管理、UI框架集成、API请求、项目优化和部署等各个方面。通过本文的指导,你应该能够顺利搭建并部署一个 Vue 3 项目。希望本文对你有所帮助,祝你在 Vue 3 的开发之旅中取得成功!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。