【Vue】手把手从0到1创建一个网站项目(Vue2)

528 阅读2分钟

前言

本项目是按照尚硅谷-尚品汇项目整理的

image.png

1.创建一个vue项目并命名

  • 执行(vue create 项目名称),如 vue create vue-web-template

  • 选择vue2版本: Default ([Vue 2] babel, eslint)

  • 选择npm方式

  • 等待创建完成

image.png

  • 这是建好的项目的目录结构
├── node_modules:项目所需依赖
├── public
│   ├── favicon.ico: 页签图标
│   └── index.html: 主页面
├── src
│   ├── assets: 存放静态资源
│   │   └── logo.png
│   │── component: 存放组件
│   │   └── HelloWorld.vue
│   │── App.vue: 汇总所有组件
│   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

2.为脚手架下载下来的项目做一些配置便于项目的开发

  • (1)设置项目启动后自动打开浏览器:在package.json中找到script,为serve属性加上--open,可以指定host,不然可能默认打开的是0.0.0.0:8080
 "scripts": {
    "serve": "vue-cli-service serve --open --host localhost",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  • (2)关闭eslint校验工具,防止写代码的过程中繁琐的eslint报错。找到vue.config.js文件(如果没有,就新建一个这个文件)
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,//关闭eslint校验
})
  • (3)src的别名设置(因为项目大的时候src(源代码文件夹):里面目录会很多,找文件不方便,设置src文件夹的别名的好处,找文件会方便一些)。创建jsconfig.json文件,将下列代码粘过来。

也有可能已经脚手架已经帮我们做好这个操作的,忽略这一步。

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "baseUrl": "./",
    "moduleResolution": "node",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  }
}

3.引入项目所需依赖

  • less npm install --save-dev less-loader less

  • vue-router npm install vue-router@3

  • axios npm install --save axios

  • vuex npm install vuex@3

  • 进度条nprogress npm install --save nprogress

  • ElementUInpm i element-ui -S

  • mock模拟数据npm install mockjs

4.启动项目,看到HelloWorld页面

npm run serve

image.png

5.搭建自己的目录结构

路由组件放在pages下,非路由组件放在components下

image.png

router配置好

//引入vue-router路由插件
import VueRouter from "vue-router"

import Home from "@/pages/Home"
export default new VueRouter({
  // 配置路由
  routes: [
    {
      path: "/home",
      component: Home,
    },
    // 项目一启动,立马重定向到home
    {
      path: "*",
      redirect: "/home",
    },
  ],
})