Vue.js并没有严格的文件和目录结构要求,但一般情况下,我们的Vue项目目录结构如下:
| ├── node_modules/ # 项目依赖的 node 模块 |
| ├── public/ # 公共资源目录 |
| │ ├── favicon.ico # 网页图标 |
| │ └── index.html # html模板(单页面应用) |
| ├── src/ # 源代码目录 |
| │ ├── assets/ # 静态资源文件夹,如图片、字体等 |
| │ ├── components/ # 公共组件 |
| │ ├── router/ # 路由文件夹 |
| │ ├── store/ # Vuex状态管理文件夹 |
| │ ├── views/ # 视图层组件 |
| │ ├── App.vue # Vue 根组件,也是整个应用的入口 |
| │ └── main.js # Vue 实例化入口文件,也是整个应用的入口 |
| ├── .babelrc # Babel 配置文件 |
| ├── .gitignore # Git管理忽略文件 |
| ├── package.json # 项目配置文件 |
| ├── README.md # 项目说明文件 |
| └── webpack.config.js # Webpack配置文件 |
复制
下面是各个核心文件的示例代码:
App.vue
| <template> |
| <div id="app"> |
| <h1>{{ title }}</h1> |
| <router-view></router-view> |
| </div> |
| </template> |
| |
| <script> |
| export default { |
| name: "App", |
| data() { |
| return { |
| title: "Vue App", |
| }; |
| }, |
| }; |
| </script> |
复制
main.js
| import Vue from "vue"; |
| import App from "./App.vue"; |
| import router from "./router"; |
| import store from "./store"; |
| |
| Vue.config.productionTip = false; |
| |
| new Vue({ |
| router, |
| store, |
| render: (h) => h(App), |
| }).$mount("#app"); |
复制
router/index.js
| import Vue from "vue"; |
| import VueRouter from "vue-router"; |
| import Home from "../views/Home.vue"; |
| |
| Vue.use(VueRouter); |
| |
| const routes = [ |
| { |
| path: "/", |
| name: "Home", |
| component: Home, |
| }, |
| { |
| path: "/about", |
| name: "About", |
| |
| component: () => import("../views/About.vue"), |
| }, |
| ]; |
| |
| const router = new VueRouter({ |
| mode: "history", |
| base: process.env.BASE_URL, |
| routes, |
| }); |
| |
| export default router; |
复制
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: { |
| increment({ commit }) { |
| commit("increment"); |
| }, |
| }, |
| getters: { |
| getCount: (state) => state.count, |
| }, |
| modules: {}, |
| }); |
复制
以上就是Vue项目的基本目录结构和核心文件的示例代码。在实际项目中,我们可以根据具体的业务需求,对文件和目录进行合理的组织和调整。