让我们创建一个简单的项目,假设我们要构建一个简单的待办事项列表应用。
首先,确保你的系统已经安装了 Node.js 和 npm。然后,按照以下步骤操作:
步骤 1:创建新项目
打开终端,执行以下命令来创建一个新的 Vue 3 项目:
npm init @vitejs/app my-todo-app --template vue
如果报错:
npm install -g create-vite
npm uninstall -g create-vite
npm install -g create-vite
再运行:
create-vite my-todo-app --template vue
然后进入项目目录
cd my-todo-app
步骤 2:安装所需的依赖项
npm install tailwindcss@latest postcss@latest autoprefixer@latest axios
步骤 3:配置 Tailwind CSS
在项目根目录创建一个文件 tailwind.config.js
,并填入以下内容:
module.exports = {
mode: 'jit',
purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
在项目根目录创建一个名为 postcss.config.cjs
的文件,并填入以下内容:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
在项目根目录创建一个名为 index.css
的文件,并将以下内容填入:
@tailwind base;
@tailwind components;
@tailwind utilities;
然后,在 index.html
文件的 <head>
标签内添加以下代码:
<link rel="stylesheet" href="./index.css">
步骤 4:编写应用代码
现在我们将创建一个简单的待办事项列表应用。
在 src
目录下创建一个名为 components
的文件夹,然后在其中创建一个名为 TodoList.vue
的文件,填入以下内容:
<template>
<div>
<h1 class="text-3xl font-bold mb-4">Todo List</h1>
<div class="mb-4">
<input type="text" v-model="newTodo" placeholder="Enter a new todo" class="p-2 border border-gray-300 rounded-md w-80">
<button @click="addTodo" class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-md">Add</button>
</div>
<ul>
<li v-for="(todo, index) in todos" :key="index" class="mb-2">
<span>{{ todo }}</span>
<button @click="removeTodo(index)" class="ml-2 px-3 py-1 bg-red-500 text-white rounded-md">Remove</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newTodo: '',
todos: [],
};
},
methods: {
addTodo() {
if (this.newTodo.trim() !== '') {
this.todos.push(this.newTodo.trim());
this.newTodo = '';
}
},
removeTodo(index) {
this.todos.splice(index, 1);
},
},
};
</script>
步骤 5:在主应用中使用组件
在 src
目录下的 App.vue
文件中使用我们创建的 TodoList
组件:
<template>
<div id="app">
<TodoList />
</div>
</template>
<script>
import TodoList from './components/TodoList.vue';
export default {
components: {
TodoList,
},
};
</script>
<style>
/* 样式 */
</style>
步骤 6:运行应用
现在,你可以在终端中运行以下命令来启动应用:
npm run dev
这将启动开发服务器,并在浏览器中打开应用。
现在,你应该能够在浏览器中看到一个简单的待办事项列表应用,你可以在输入框中输入新的待办事项,并点击添加按钮,然后点击每个待办事项旁边的删除按钮来删除它。
启动的 本地,访问地址:
http://localhost:5173
使用nginx反向代理:
server {
listen 80;
server_name vite.com;
root "C:/vue_work/my-todo-app";
location / {
proxy_pass http://localhost:5173;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}