天天看點

前端架構Vue入門

簡介

Vue 是一套用于建構使用者界面的漸進式架構。與其它大型架構不同的是,Vue 被設計為可以自底向上逐層應用。Vue 的核心庫隻關注視圖層,不僅易于上手,還便于與第三方庫或既有項目整合。另一方面,當與現代化的工具鍊以及各種支援類庫結合使用時,Vue 也完全能夠為複雜的單頁應用提供驅動。

環境安裝

環境準備:

node

npm

vue-cli

vue-devtools

nvm安裝: 用來管理node版本

下載下傳chrome 插件位址:

https://chrome-extension-downloader.com/

BootCDN: https://www.bootcdn.cn/

模闆文法

  1. vue 檔案結構(template,script, style)
  2. 插值文法 {{msg}}, 資料, js表達式
  3. 指令(指令縮寫)@click :href
<!DOCTYPE html>     <html lang="en">     <head>         <meta charset="UTF-8">         <title>Title</title>     	<style>     		.bg{     			color: red;     		}     	</style>     	<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script></head>     <body>     <div id="app">     <div class="bg" v-bind:id="bg1">     	hello world!     	{{msg}}     </div>     <div class="bg">     	{{msg}}     </div>     	{{count}}     	{{(count + 1)*10}}     <div v-html="template">     </div>     <a :href="url">百度</a>     <!--v-bind:綁定頁面屬性, 可以直接縮寫 :-->     	<button type="button" @click="submit()">數字加1</button>     <!--v-on:事件 縮寫@	-->     </div>     <script>     	new Vue({            el:'#app', // .bg     	   data: {                msg: 'hello vue!!',     		   count: 1,     		   template: '<div>hello template</div>',     		   url: 'https://www.baidu.com/',     		   bg1: 'app-bind'     	   },     	   methods: {                submit: function() {                    this.count ++     		   }     	   }     	})     </script>     </body>     </html>           

計算屬性與偵聽器

  1. 計算屬性: conputed
  2. 偵聽器: watch

偵聽器:

<script>     	var app = new Vue({            el:'#app', // .bg     	   data: {                msg: 'hello vue!!',     		   count: 1,     		   template: '<div>hello template</div>',     		   url: 'https://www.baidu.com/',     		   bg1: 'app-bind'     	   },     	   methods: {                submit: function() {                    this.count ++     		   }     	   },     	   watch: {                msg: function (newVal, oldVal) {     			   console.log('newVal is:' + newVal)     			   console.log('oldVal is:' + oldVal)                }     	   }     	})     </script>           

給Vue 對象一個變量,這樣就可以在chrome console 裡進行調試了,下面是針對watch屬性的一個使用調試:

當改變app.msg的值後,就會調用watch 對應的function函數,列印相關資訊

app.msg     "hello vue!!"     app.msg = "new message!!"     index.html:49 newVal is:new message!!     index.html:50 oldVal is:hello vue!!     "new message!!"           

計算屬性

computed 中的相關屬性任意值發生變化都會影響msg1值的變化

監聽的值都是本執行個體中的值

watch: {        msg: function (newVal, oldVal) {     	   console.log('newVal is:' + newVal)     	   console.log('oldVal is:' + oldVal)        }     },     computed: {        msg1: function () {     	   return 'computed ' + this.msg + ',' + this.another        }     }           

watch 監聽的一般是單一的變量或數組--異步場景

computed 可以監聽很多變量,并且這些變量一定是Vue裡的 -- 資料關聯

條件渲染、清單渲染、Class與Style綁定

v-if|| v-show 用法

<div id="app">     	<div v-if="count > 0">     		判斷1:count大于0,count的值是:{{count}}     	</div>     	<div v-else-if="count < 0 && count > -5">     		判斷2:count的值是:{{count}}     	</div>     	<div v-else>     		判斷3:count的值是:{{count}}     	</div>     	<div v-show="count == -1">show: {{count}}</div>     </div>     script>     	var app = new Vue({            el:'#app', // .bg     	   data: {     		   count: 1     	   }     	})     </script>           

根據條件判斷是否展示相關内容

v-for

<div v-for="item in list"> {{item}}</div>     <script>     		var app = new Vue({     		   el:'#app', // .bg     		   data: {     			   msg: 'hello vue!!',     			   count: 1,     			   list: [1,2,3,4,5]     		   })     </script>           

v-for 與 v-if、v-show 結合使用:

<div v-for="item in list">     		<div v-if="item.age > 29">     			{{item.name}}     		</div>     		<div v-else>     			{{item.age}}     		</div>     	    <div v-show="item.age > 29">                 {{item.name}}     		</div>     	</div>           

Class與Style的綁定

Style 綁定:

<div v-show="item.age > 29" v-bind:style="styleMsg">                 {{item.name}}     	</div>     	<script>     		var app = new Vue({     		   el:'#app', // .bg     		   data: {     		       styleMsg:{     		         color: 'red',     			     textShadow: '0 0 5px green'     			   },     			   msg: 'hello vue!!'     		   })     </script>           

class 綁定:

<div v-show="item.age > 29"     			 :class="['active', 'add', 'more', {'another':item.age < 30}]"     			 :style="styleMsg">                 {{item.name}}     </div>           

item.age < 30 的時候,another 才會展示出來

Vue-Cli

安裝:

npm install -g @vue/cli           

檢視版本:

vue --version           

如何建立工程:

vue create project           

or

vue ui    // 可視化建立項目           

vue 項目的目錄結構:

-- public     -- src     -- package.json           

元件化思想

元件主要實作功能子產品的複用

可以很高效的執行

可以将一些複雜的頁面邏輯進行拆分

如何進行拆分:

  1. 業務代碼行不超過300行原則
  2. 複用原則

元件帶來的問題:

1.元件狀态管理(vuex)

2.多元件的混合使用,多頁面,負責業務(vue-router)

3.元件間的傳參、消息、事件管理(props,emit/on,bus)

vue 代碼風格

https://cn.vuejs.org/v2/style-guide/

vue-router

  1. views 下建立相關vue 檔案
  2. 在route.js裡配置相關路由
{     				path: '/data',     				name: '資料',     				icon: 'dashboard',     				component: PageLayout,     				children: [     					{     						path: '/data/info',     						name: '詳情',     						icon: 'none',     						component: () => import('@/views/data/Info')     					}]     			}           

3.在相關頁面配置vue檔案需要展示的地方

vuex

場景:

  1. 多個視圖依賴于同一個狀态(如菜單導航)
  2. 不同視圖的行為需要變更同一狀态(如評論彈幕)

為vue.js開發的狀态管理模式

元件狀态統一管理

元件狀态改變遵循統一的規則

使用需要做如下幾步:

  1. 定義store.js 檔案
import Vue from 'vue'     import Vuex from 'vuex'     Vue.use(Vuex);     export default new Vuex.Store({     	state: {     		count: 0     	},     	mutations: {     	   increase() {     	   	this.state.count ++     	   }     	},     	actions: {     	}     });           

state: 元件公用的狀态

mutations: 定義改變狀态的方法

2.元件中使用,需要引入store.js 檔案

import store from '@/store/index'     export default {     name: "About",     store,     methods: {     	add() {     		console.log("add")     		store.commit('increase')     	}         }     }     </script>           

store.commit() 送出修改

3.元件之間使用

在另一個檔案使用狀态

<template>         <div>     		<p>{{msg}}</p>     	</div>     </template>     <script>     	import store from '@/store/index'         export default {             name: "Config",     		store,     		data () {                 return {                    msg: store.state.count                 }     		}         }     </script>     <style scoped>     </style>           

如何進行調試

vue 有Chrome 插件

在需要調試的地方寫上debugger

檢視vue 變量的值可以直接在chrome console 裡,寫this.變量(debug模式下)

chrome Network-xhr 檢視相關請求

調試互動可以使用 Fast 3G | Slow 3G

可以把目前元件的this對象綁定到windows這個全局變量裡去

mounted() {       window.vue = this     },     methods: {     	add() {     		console.log("add")     		debugger     		store.commit('increase')     	},     	output() {     	    console.log("output")     	}         }     }           

就可以直接在chrome console裡列印

window.vue.output()

如何內建vue.js

  • 單頁面、多頁面引入vue.js CDN
  • 複雜單頁面 vue cli 工具建立模闆項目

開發工作流:

  • 需求調研(确定需求)
  • 互動設計、邏輯設計、接口設計
  • 代碼實作、 測試運作、線上部署

GIT:

  • 建立項目 git clone, git init
  • 建立分支,推送分支,合并分支
  • 删除分支,回退版本
git add . # 添加需要送出的檔案     git commit -m "first commit" # 送出需要push的檔案     git remote -v     # 可以看到遠端的倉庫     git push origin master     git branch -a  # 檢視所有分支     git checkout -b dev #建立分支     git push origin dev # 送出到dev分支     -- 合并 分支 --     git checkout master     git merge dev     git push origin master     git branch -D dev # 删除dev分支     git push origin :dev # 删除遠端分支     git reset --hard head^  # 退回到上一個版本     git log | git reflog  #檢視之前的git 記錄     git reset --hard HEAD@{1}  # 回退到任意版本           

一個簡單的單頁面應用

代碼:

<template>         <div>     		<p>{{msg}}</p>     		<ul>     			<li v-for="(item, index) in lists"     				:key ="index"     				@click="choose(index)"     				:class="{active: index === current && current !==''}"     			>     				{{item}}     			</li>     		</ul>     		<button type="button" @click="add()">添加</button>     		<ul>     			<li v-for="(item, index) in target"     				:key ="index"     			>     				{{item}}     			</li>     		</ul>     	</div>     </template>     <script>     	import store from '@/store/index'         export default {             name: "Config",     		store,     		data () {                 return {                    msg: store.state.count,     			   lists: [1,2,3,4,5],     			   target: [],     			   current: ''                 }     		},     		methods: {             	choose(index) {             		this.current = index             	},     			add() {             	    if (this.current==='') {return}             	    this.target.push(this.lists[this.current])     				this.current=''     			}     		}         }     </script>     <style scoped>     	li.active {     		background: green;     	}     </style>           

效果圖:

前端架構Vue入門

如何高仿别人的App

  • 審查元素 可以檢視相應的Dom 結構
  • Header,Body 裡面檢視JS、CSS引用,搜尋相應的js庫
  • 也可以檢視chrome Network|Source中的js,使用反編與斷點進行調試 針對壓縮的js檔案,chrome 提供了format 功能

打包釋出

項目打包:

npm run  build           

打包完成後,把dist檔案夾下所有的檔案上傳到伺服器的根目錄裡去,就可以通路了

總結

本文主要講解了vue架構的一些入門知識,vue 開發環境的搭建安裝、打包釋出,vue的模闆文法,開發流程以及vue的相關元件使用,如何進行調試,至此就可以開發一些簡單的單頁面應用了。

本文作者: chaplinthink, 關注領域:大資料、基礎架構、系統設計, 一個熱愛學習、分享的大資料工程師