給學生黨的vue教程(vue全家桶+Element)

這個教程只是給我妹妹寫的課外作業,並沒有太多高級東西,只適合於有點前端基礎的小白,
忠於興趣,誠待文字,取悅自己,理解他人。

01-- 項目準備

01-1 安裝

1兼容性 :Vue 不支持 IE8 及以下版本,因爲 Vue 使用了 IE8 無法模擬的 ECMAScript 5 特性。但它支持所有兼容 ECMAScript 5 的瀏覽器
2直接用 <script> 引入

3[CDN]https://cn.vuejs.org/v2/guide/installation.html#CDN "CDN"對於製作原型或學習,你可以這樣使用最新版本:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

對於生產環境,我們推薦鏈接到一個明確的版本號和構建文件,以避免新版本造成的不可預期的破壞:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

如果你使用原生 ES Modules,這裏也有一個兼容 ES Module 的構建文件:

<script type="module">
  import Vue from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js'
</script>

你可以在 cdn.jsdelivr.net/npm/vue 瀏覽 NPM 包的源代碼。

4NPM在用 Vue 構建大型應用時推薦使用 NPM 安裝[1]。NPM 能很好地和諸如 webpackBrowserify 模塊打包器配合使用。同時 Vue 也提供配套工具來開發單文件組件

# 最新穩定版
$ npm install vue
# vue版本號
$ npm install vue@vue版本號

沒有環境的可以參考
既然我們要用npm裝包就需要一個package.json 來記錄存放第三方包的依賴

# 創建一個空的文件夾
$ mkdir vue-maer
$ cd vue-maer
# 然後,調用 npm init 來初始化 package.json,
# 參數 -y 表示對 npm 要求提供的信息,都自動按下回車鍵,表示接受默認值
$ npm init -y  

基礎規範,我們的項目最好不要用中文命名

#i 是 install 的縮寫
$ npm i vue

01-2使用vueCLI創建項目

$ vue create vue-admin
------------
# 第一步:選擇創捷模式
Vue CLI v3.9.1
┌───────────────────────────┐
│  Update available: 4.2.2  │
└───────────────────────────┘
? Please pick a preset: (Use arrow keys)
# 默認自動選擇模式
  default (babel, eslint)
#手動選擇模式
>  Manually select features
------------
# 第二步
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Babel   #將ECMAScript6轉化爲ECMAScript5的一個工具
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 (*) Router   #vue初始路由
 ( ) Vuex
 (*) CSS Pre-processors #css預處理器
 (*) Linter / Formatter #代碼校驗格式化
 ( ) Unit Testing
 ( ) E2E Testing
------------
# 第三步--使用路由模式(history)
? Use history mode for router? (Requires proper server setup for index fallback in production) 
(Y/n) n
------------
# 第四步--選擇css預處理器
 Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
  Sass/SCSS (with dart-sass)
  Sass/SCSS (with node-sass)
> Less
  Stylus
------------
# 第五步--選擇代碼驗證格式風格
? Pick a linter / formatter config: (Use arrow keys)
  ESLint with error prevention only
  ESLint + Airbnb config
> ESLint + Standard config
  ESLint + Prettier
------------
# 第六步--選擇代碼校驗方式
? Pick additional lint features:
>(*) Lint on save 文檔保存的時候,會進行格式驗證
 (*) Lint and fix on commit  在進行git commit 時候,會進行代碼校驗,並且嘗試自動解決錯誤語法
------------
# 第七步--選擇配置註冊
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?
> In dedicated config files 獨立配置文件
  In package.json 註冊到package.json當中。但維護比較麻煩
------------
# 第八步--是否進行模板化
? Save this as a preset for future projects? (y/N) n
將此保存爲將來項目的預設?(是/否)否
#根據提示進行啓動項目
 $ cd vue-admin
 $ npm run serve

2020年2月2日更新

01-3目錄結構

├── README.md            項目介紹
├── index.html           入口頁面
├── build              構建腳本目錄
│  ├── build-server.js         運行本地構建服務器,可以訪問構建後的頁面
│  ├── build.js            生產環境構建腳本
│  ├── dev-client.js          開發服務器熱重載腳本,主要用來實現開發階段的頁面自動刷新
│  ├── dev-server.js          運行本地開發服務器
│  ├── utils.js            構建相關工具方法
│  ├── webpack.base.conf.js      wabpack基礎配置
│  ├── webpack.dev.conf.js       wabpack開發環境配置
│  └── webpack.prod.conf.js      wabpack生產環境配置
├── config             項目配置
│  ├── dev.env.js           開發環境變量
│  ├── index.js            項目配置文件
│  ├── prod.env.js           生產環境變量
│  └── test.env.js           測試環境變量
├── mock              mock數據目錄
│  └── hello.js
├── package.json          npm包配置文件,裏面定義了項目的npm腳本,依賴包等信息
├── src               源碼目錄  
│  ├── main.js             入口js文件
│  ├── app.vue             根組件
│  ├── components           公共組件目錄
│  │  └── title.vue
│  ├── assets             資源目錄,這裏的資源會被wabpack構建
│  │  └── images
│  │    └── logo.png
│  ├── routes             前端路由
│  │  └── index.js
│  ├── store              應用級數據(state)
│  │  └── index.js
│  └── views              頁面目錄
│    ├── hello.vue
│    └── notfound.vue
├── static             純靜態資源,不會被wabpack構建。
└── test              測試文件目錄(unit&e2e)
  └── unit              單元測試
    ├── index.js            入口腳本
    ├── karma.conf.js          karma配置文件
    └── specs              單測case目錄
      └── Hello.spec.js

2020年2月4日更新

01-4 入口模型

  • 找到main.js入口模型
import Vue from 'vue'
import App from './App.vue'
import router from './router' //加載路由

Vue.config.productionTip = false

new Vue({ //創建vue實例
  router, //綁定路由
  render: h => h(App)// 將app根主件
}).$mount('#app')//替換到頁面的#app節點上
  • 在入口模塊中
    • 加載根組件
    • 加載路由
    • 創建vue實例
    • 根據組件替換到頁面中 #app節點

01-5 git版本控制

git的基本使用就不在這裏講述了有興趣的請看git 連接遠程倉庫如有疑問請聯繫我
我就描述項目過程:

 #拷貝項目到本地
 git clone [email protected]:dileigege/dileigege-vue-admin.git
 #將隱藏文件git 複製到項目 
 git add .
 git  status
 git commit -m "提交日誌-初始化"
 #項目就我一個人,所以我就用主分支
 git push


2020年3月10日更新
最近接了項目,就停更了。項目今天后繼續更新

01-6 目錄整合

App.vue 調整
切記由於我們的項目使用了 eslintrc所以我們必須按照規範寫,也許這個你覺的很麻煩,但是你可知道你不規範代碼可能增加夥伴的工作。eslintrc

<!--  -->
<template>
  <div></div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {}
  }
}
</script>

<style lang='less' scoped>
</style>

views components文件夾內的文件,清空不需要了
router路由調整(用我們自己的項目需求調整)

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
]

const router = new VueRouter({
  routes
})

export default router

④項目目錄補充

  1. api目錄 接口封裝模塊
  2. directive 指令目錄
  3. filters 過濾器目錄
  4. store 狀態容器模塊
  5. styles 樣式目錄
  6. utils 工具模塊

⑤引用靜態文件將圖片資源放置 assets , public中,引用字體文件在public - index.html

2020年3月12日更新

01-7 導入Element

npm 安裝
推薦使用 npm 的方式安裝,它能更好地和 webpack打包工具配合使用。

npm i element-ui -S
---安裝成功--
dependencies": {
    "core-js": "^3.6.4",
    "element-ui": "^2.13.0",
    "vue": "^2.6.11",
    "vue-router": "^3.1.5"
  },

爲了更好的食用,請按照個人項目進行.eslintrc.js可以參考食用

1ESLint 配置文件 .eslintrc 示例及說明
2錯誤提示

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard'
  ],
  parserOptions: {
    parser: 'babel-eslint'
  },
  rules: {
    "space-before-function-paren": 0,
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    "space-before-function-paren": ["error", {
       "anonymous": "always",
       "named": "always",
       "asyncArrow": "always"
     }],
     'semi':['err','always']
  }
}

你可以引入整個 Element,在main.js 中寫入以下內容:完整內容

import Vue from 'vue'
import App from './App.vue'
import router from './router'
// 完整引用Element
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.config.productionTip = false
Vue.use(ElementUI);

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

App.vue頁面添加Element

<template>
  <div>
    <el-row>
      <el-button round>圓角按鈕</el-button>
      <el-button type="primary" round>主要按鈕</el-button>
      <el-button type="success" round>成功按鈕</el-button>
      <el-button type="info" round>信息按鈕</el-button>
      <el-button type="warning" round>警告按鈕</el-button>
      <el-button type="danger" round>危險按鈕</el-button>
</el-row>
  </div>
</template>

2020年3月13日更新

02項目開始

02-1登陸板塊

主要步驟:頁面佈局 驗證碼 提交登陸 表單驗證
我們的項目主要是應用Element,但在一些項目中,UI給我們的設計圖,ElementUI並不能滿足,所以我們就需要做一些調整

02-1-1 畫UI

本人不是專業UI,所以能看就行,請專業的不喜勿噴,都是公司的壓迫層,更應該相親相愛,畢竟我們可能是唯一理解你們“五彩斑斕黑”的人

02-1-2 登陸組件及路由配置

首先我們先在view文件夾創建兩個組件模塊,Login - index.vue home - index.vue 這裏的view可以狹義的理解爲 mvc中的視圖層,MVC是後端世界中一種經典的設計模式,全名爲Model-View-Controller,即模型-視圖-控制器,去過vue官網幾次的人就知道,vue的設計模式是MvvM,有點多了,我們專注項目。
3-0對vue核心的理解 MVVM
文件router-inde.js首頁路由和登陸頁路由

const routes = [
  {
    name: 'home',
    path: '/',
    component: () => import('@/views/home')
  },
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login')
  }
]

app.vue調用路由組件

<template>
  <div>
    <router-view/> 調用組件
  </div>
</template>

02-1-3 頁面編寫

login-index.vue頁面 表單組件

<el-form ref="form" :model="form" label-width="80px">
  <el-form-item label="活動名稱">
    <el-input v-model="form.name"></el-input>
  </el-form-item>
  <el-form-item label="活動區域">
    <el-select v-model="form.region" placeholder="請選擇活動區域">
      <el-option label="區域一" value="shanghai"></el-option>
      <el-option label="區域二" value="beijing"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="活動時間">
    <el-col :span="11">
      <el-date-picker type="date" placeholder="選擇日期" v-model="form.date1" style="width: 100%;"></el-date-picker>
    </el-col>
    <el-col class="line" :span="2">-</el-col>
    <el-col :span="11">
      <el-time-picker placeholder="選擇時間" v-model="form.date2" style="width: 100%;"></el-time-picker>
    </el-col>
  </el-form-item>
  <el-form-item label="即時配送">
    <el-switch v-model="form.delivery"></el-switch>
  </el-form-item>
  <el-form-item label="活動性質">
    <el-checkbox-group v-model="form.type">
      <el-checkbox label="美食/餐廳線上活動" name="type"></el-checkbox>
      <el-checkbox label="地推活動" name="type"></el-checkbox>
      <el-checkbox label="線下主題活動" name="type"></el-checkbox>
      <el-checkbox label="單純品牌曝光" name="type"></el-checkbox>
    </el-checkbox-group>
  </el-form-item>
  <el-form-item label="特殊資源">
    <el-radio-group v-model="form.resource">
      <el-radio label="線上品牌商贊助"></el-radio>
      <el-radio label="線下場地免費"></el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="活動形式">
    <el-input type="textarea" v-model="form.desc"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmit">立即創建</el-button>
    <el-button>取消</el-button>
  </el-form-item>
</el-form>
<script>
  export default {
    data() {
      return {
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        }
      }
    },
    methods: {
      onSubmit() {
        console.log('submit!');
      }
    }
  }
</script>

既然UI框架給了我們樣式,我們就使用UI框架給的樣式,不符合樣式的我們可以進行調整,效率在我們的工作中也很重要。
style-style.less AND main.js

/*
 * @description:  公共樣式 
 * @param : NO
 * @return: NO
 */
html,
body,
ul,
li,
ol,
dl,
dd,
dt,
p,
h1,
h2,
h3,
h4,
h5,
h6,
form,
fieldset,
legend,
img {
    margin: 0;
    padding: 0;
}
// 清除浮動
clearfix {
    *zoom: 1;

    /*ie*/
    &::after,
    &::before {
        content: '';
        display: table;
    }

    &::after {
        clear: both;
    }
}
// .box7 {
//     @extend %clearfix;
// }

 html , body {
     height: 100%;
 }

在main.js中添加
import './styles/style.less'

樣式就大家想怎麼寫就怎麼寫吧,如果樣式寫不了,我建議你去再學學,HTML+css吧,雖然說這兩個寶貝並不難,但也並不簡單,


2020年3月21日更新

02-1-4 驗證碼操作

模擬接口

<!--  @click="ongaincode"  -->
<el-button round class="button-fler" @click="ongaincode">
  獲取驗證碼
</el-button>
import axios from 'axios';
  methods: {
    onSubmit () {
    //提交按鈕觸發 
      console.log('submit!');
    },
    ongaincode () {
      // console.log('ongaincode!');
      //驗證碼按鈕觸發 
      axios({
        method: 'GET',
        url: '接口,可用yapi模擬,'
      }).then(res => {
        console.log(res.data)
      })
    }
  }

返回數據,可以使用


當然一個真實的驗證中,我們可以使用一些驗證工作,我們可以使用後端寫的驗證規則,也可以使用一些工具,爲了保證我們的手機號,不會被惡意強刷,造成一些沒有必要的損失。
2020年3月25日更新

02-1-5 驗證碼操作

styl邏輯

//在data中添加定時器與定位時間
  codeTime: null,
  codeNumer: 20
//在methods內添加 驗證碼倒計時
    countDown() {
      // console.log("驗證碼倒計時")
      this.codeTime = window.setInterval(() => {
        this.codeNumer--;
        if (this.codeNumer <= 0) {
          // 清除定時器
          window.clearInterval(this.codeTime);
          //定時器 還原
          (this.codeNumer = 20), (this.codeTime = null);
        }
      }, 1000);
    }

html樣式

 <!-- !!codeTime 返回爲布爾,定時器爲數字 一個!爲ture 兩個取反 -->
!!codeTime
     <el-button
            round
            class="button-fler"
            @click="ongaincode"
            :disabled="!!codeTime"
          >{{ codeTime ? `剩餘${codeNumer}秒`: '獲取驗證碼'}}</el-button>
        </el-col>

2020年3月28日更新

02-2-1 Layout佈局

按照正常程序的話下一步應該是路由守衛,但是考慮到每次都登陸太麻煩了,so就先不佈局,然後最後寫路由守衛
view - Layout - index

<template>
<el-container>
  <el-header>
    <layHeader/>
  </el-header>
  <el-main>
      <layTopnav/> 
    Main
    </el-main>
  <el-footer>Footer</el-footer>
</el-container>

</template>
<script>
 // 引入子組件
import  layTopnav from './comments/layTopnav';
import  layHeader from './comments/layHeader';
export default {
  name: 'app',
//註冊 layTopnav layHeader
  components: {
   layTopnav,
   layHeader
  },
  data() {
    return {}
  }
}
</script>
<style lang='less' scoped>
.el-container{
  width: 100%;
  .el-header{
  background-color: #2375FF;
}
 .el-main{
   background-color: #ffffff;
 }
 .el-footer{
   position:absolute;
   width: 100%;
   background-color: #333333;
   bottom: 0;
 }
}

</style>

view - Layout - comments - layHeader.vue

 <template>
   <div>
       layheader組件
   </div>
 </template>
 
 <script>
 export default {
   name: 'layHeader',
   data() {
     return {}
   }
 }
 </script>
 <style lang='less' scoped>
 </style>

view - Layout - comments - layTopnav.vue

 <template>
   <div>
       layTopnav.vue組件
   </div>
 </template>
 
 <script>
 export default {
   name: 'layTopnav',
   data() {
     return {}
   }
 }
 </script>
 <style lang='less' scoped>
 </style>

在router.js路由進行註冊

 {
      name: 'Layout',
      path: '/',
      component: () => import('@/views/Layout')
    },

2020年4月1日更新

02-2-2 首頁佈局

** 安裝 v-charts **

npm i v-charts echarts -S

完整使用:main.js

// 使用v-charts
import VCharts from 'v-charts'
// 引用全部VCharts
Vue.use(VCharts)

使用

<template>
  <ve-pie :data="chartData" :settings="chartSettings"></ve-pie>
</template>

<script>
  export default {
    data () {
      this.chartSettings = {
        roseType: 'radius'
      }
      return {
        chartData: {
          columns: ['日期', '訪問用戶'],
          rows: [
            { '日期': '1/1', '訪問用戶': 1393 },
            { '日期': '1/2', '訪問用戶': 3530 },
            { '日期': '1/3', '訪問用戶': 2923 },
            { '日期': '1/4', '訪問用戶': 1723 },
            { '日期': '1/5', '訪問用戶': 3792 },
            { '日期': '1/6', '訪問用戶': 4593 }
          ]
        }
      }
    }
  }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章