志宇-Vue2学习
Vue2
- vue的使用
- vue雙向綁定
- vue指令
- vue事件
- vue綁定
- vue鉤子函數
- vue過濾器
- 數據監聽watch
- 計算屬性 computed
- vue配套的ajax
- vue組件
- vue父子傳值
- 非父子組件傳值(兄弟組件傳值)
- vue中的路由
- vue路由傳值
- vue路由嵌套
- require 使用說明
- webpack 使用說明
- css 處理語言
- babel-loader
- vue-cli2和vue-cli3區別
- vue腳手架 vue-cli2安裝項目
- vue腳手架 vue-cli3
- vue-cli 安裝和打包
- vue-cli 3.0配置
- VueX
- VueX能做什么
- 結構
- 使用
- Vue 創建項目
vue的使用
vue雙向綁定
Mvvm
M是數據, V是顯示,
Vm是調度者 從m層獲取數據 然后給 v層顯示,從 v層獲得數據 然后給 m層保存
在jquery中是通過抓取dom對象,通過修改dom對象中屬性來修改信息,在vue中通過直接操作數據即可改變信息,不用再去抓取dom對象了
new Vue({el:目的地,template:模板內容})
{{ data里的變量 }}
vue指令
v-text 不可解析html標簽
v-html 可解析html標簽
v-if 做元素的插入(append)和移除(remove)操作
v-else-if
v-else
v-show display:none 和display:block的切換
自定義指令
vue事件
<div id="app">//事件都有 keydown keyup click dbclick<input type="button" value="添加" v-on:click="add"/><input type="button" @click="add" value="添加" /></div>var app=new Vue({el:'#app',data:{id:''},methods:{add(){this.list.push({id:this.id,name:this.name,time:new Date});}});vue綁定
<input v-bind:value="name" v-bind:class="name"> //單項綁定 v-bind就是對屬性的簡單賦值,當內存中值改變,還是會觸發重新渲染<input v-model="name" v-bind:class="name"> //v-model 雙向數據綁定(value改變內存中的值也隨著改變),v-model只是綁定value屬性vue鉤子函數
beforeCreate 數據沒有初始化
created 可以操作數據
beforeMount 還未生成DOM
mounted 可以操作DOM
beforeUpdate 可以二次修改
updated 可以獲取最終數據
beforeDestroy
destroyed
vue過濾器
全局過濾器Vue.filter(‘過濾器名’,過濾方式fn );
組件內的過濾器 filters:{ ‘過濾器名’,過濾方式fn }
{{ msg | 過濾器名}}
數據監聽watch
<div id="app"><div>watch監聽數據,當下面文本框輸入love會提示</div><input type="text" name="" v-model='msg.text'><div>computed計算屬性</div>(<input type="text" name="" v-model='n1'>+<input type="text" name="" v-model='n2'>) ={{result}}</div>new Vue({el:'#app',data(){return {msg:{text:''},n1:'',n2:''}},computed:{result(){return Number(this.n1)+Number(this.n2)}},watch:{// msg(newval,oldval){// if(newval.text=='love'){// alert(newval.text)// }// }msg:{//每次msg改變都會觸發handler方法handler(newval,oldval){if(newval.text=='love'){alert(newval.text)}},//不開啟深度監聽如果監聽的是數組則可能監聽不到deep:true}}})計算屬性 computed
<div id="app">{{priceInTax}} </div>var app=new Vue({el:'#app',data:{price:100,},computed:{priceInTax:function(){return this.price * 2.00;}}});vue配套的ajax
axios.get('/user?ID=12345').then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});vue組件
<html><head><meta charset="UTF-8"><title></title><script src="js/vue.js"></script></head><body><div id="app"><first-component></first-component><!--創建組件時采用駝峰命名privateComponent 在調用組件時將大寫字母換成 -小寫字母--><private-component></private-component><ol><!--將遍歷的所有game數組中的數據item 傳入--><my-component v-for="item in game" :game="item"></my-component></ol><button-component></button-component><button-component></button-component><br></div><script>//定義的第一個全局組件var firstComponent=Vue.extend({template:'<h1>這里是第一個組件</h1>'});Vue.component('first-component',firstComponent);//定義的第二個全局組件Vue.component('my-component',{// 在標簽上傳遞過來的值props:['game'],template:'<li>{{game.title}}</li>'});//定義一個button-component組件var buttonComponent=Vue.extend({template:'<button @click="add">你點擊了{{msg}}次</button>',//這里的data必須是方法,不能是屬性,因為方法是私有的,屬性則是公共使用的data(){return { msg:'1'}},methods:{add(){this.msg++;}}});Vue.component('button-component',buttonComponent);var app=new Vue({el:'#app', data:{game:[{title:'第一個'},{title:'第二個'},{title:'第三個'}]},methods:{},components:{//定義的私有組件'privateComponent':{template:'<h1>這里是一個私有組件</h1>'},},});</script></body> </html>vue父子傳值
父傳子
子組件中聲明一個props:[‘屬性名’],父組件使用組件時傳入屬性
子傳父
子組件方法中調用 this.$emit(‘調用事件’,傳遞參數)
父組件使用子組件時 聲明傳值要調用的方法
<children @調用事件=‘要調用的父組件中的方法’> < /children>
非父子組件傳值(兄弟組件傳值)
<html><head><meta charset="UTF-8"><title></title><script src="js/vue.js"></script><!--父組件向子組件中傳值--></head><body><div id="app"></div><script>//首先創建一個實例用于綁定監聽事件,實例名隨便起 這里起名為$busVue.prototype.$bus=new Vue();var myHead={template:`<div>這里是頭部數據 {{headMsg}}</div>`,data(){return {headMsg:'頭部數據'};},//鉤子函數 數據初始換完成時 dom對象還沒有初始化時created(){//監聽$bus對象上的sendMessage事件,如果有調用則觸發方法var self=this;// this.$bus.$on('sendMessage',function(val){// this.headMsg=val; 如果這里的this代表的是this.$bus對象,并不是myHead對象// });self.$bus.$on('sendMessage',function(val){self.headMsg=val;});}};var myBody={template:`<div>這里是尾部數據 <button @click='sendMsg(bodyMsg)'>向頭部傳遞數據</button></div>`,data(){return {bodyMsg:'尾部數據'};},methods:{sendMsg(bodyMsg){//調用$bus實例的 sendMessage方法this.$bus.$emit('sendMessage',bodyMsg);}}};var app=new Vue({el:'#app',template:`<div><my-head></my-head><my-body></my-body></div>`,methods:{},components:{// myHead和 myBody是兄弟組件myHead,myBody},});</script></body> </html>vue中的路由
用于頁面跳轉
vue-router中的對象: $route 路由信息對象,只讀對象 $router 路由操作對象,只寫對象 this.$router.push() 跳轉到指定的url,會向history插入新記錄 this.$router.replace() 同樣是跳轉到指定的url,但是這個方法不會向history里面 添加新的記錄,點擊返回,會跳轉到上上一個頁面。上一個記錄是不存在的。 this.$router.go(-1) 常用來做返回,讀history里面的記錄后退一個 vue的路由有兩種模式,1種是history,1中是hashhistory看上局更簡潔,使用后期容易出現問題(打包時候、ios兼容問題、后端跳轉前端路徑問題)hash使用簡單,后期ios兼容問題方便解決 <html><head><meta charset="utf-8"><title></title><script src="js/vue.js"></script><script src="vue-router.js"></script></head><body><div id="app"><!--兩種通過路由跳轉方式 第一種通過<a href=''></a> 方式跳轉第二種通過<router-link> 進行跳轉--><a href="#/login">登錄</a> | <a href="#/regist">注冊</a> | <router-link to="/login" tag="span">通過 router-link 跳轉到登錄</router-link> |<button @click='goTo'>通過方法跳轉到登錄</button> | <button @click='goToNoInsertHistory'>跳轉到注冊,跳轉記錄不插入history</button> | <button @click='goBefore'>跳轉到history的上一個記錄</button><!--routerView 是用來顯示數據的位置--><router-view></router-view> </div><script>window.onload=function(){//當通過<a href=''></a> 方式跳轉時 vue底層通過這種方式進行切換dom頁面元素window.addEventListener('hashchange', function(e) {console.log(location.hash)// switch(location.hash==''){// dom.innerHTML="";// }})}var login={template:'<h1>登錄</h1>', }var regist={template:'<h1>注冊</h1>',}//當導入了vue-router之后 window 全局對象中就有了一個路由構造函數 叫 VueRoutervar routerObj=new VueRouter({//創建路由對象routes:[//路由匹配規則//每個路由規則,都是一個對象,這個規則對象身上必須的兩個屬性://1是path 表示監聽哪個路由鏈地址//2是component 如果路由匹配到path則展示component屬性對應的那個組件{path:'/',redirect:'/login'},{path:'/login',component:login//component的屬性值必須是一個組件模板對象,不能是組件的引用名稱},{path:'/regist',component:regist}]}); var app=new Vue({el:'#app',data:{},methods:{goTo(){//跳轉this.$router.push({path:'/login'});},goToNoInsertHistory(){//跳轉 同時跳轉記錄不插入到history中this.$router.replace({path:'/regist'})},goBefore(){//跳轉到上一個頁面(history中的上一個頁面)this.$router.go(-1)}},router:routerObj // 將路由規則對象,注冊到vm實例上,用來監聽url地址變化 然后用來展示對應組件});</script></body> </html>vue路由傳值
傳遞兩種參數 1.查詢參 2.路由參數 **1.查詢參** router-link標簽中配置(傳參) :to="{name:'login',query:{id:loginid}}" 組件中獲取(取參) this.$route.query.id **2.路由參數** router-link標簽中配置(傳參) :to="{name:'路徑',params:{id:registerid}}" 配置路由的規則 { name:'路徑',path:'/路徑/:id'} 組件中獲取(取參) this.$route.params.id **3.路由參數** router-link標簽中配置(傳參) :to="{name:'路徑',params:{id:registerid}}" 配置路由的規則 { name:'路徑',path:'/路徑/:id',props:true} 在組件中聲明 props:['id(這里的id指的是參數名)'] 組件中獲取(取參) 直接使用參數{{id}} 因為在路由中配置了props:true 總結: :to傳參的屬性里 params是和name配對的 query和name或path都可以 (使用params傳參,router-link必須通過name跳轉) 使用路由參數必須要配置路由規則里面配置好參數名,否則刷新頁面參數會丟失 <html><head><meta charset="utf-8"><title></title><script src="js/vue.js"></script><script src="vue-router.js"></script></head><body><div id="app"><!--路由中查詢參參數傳遞 必須使用query參數--><router-link :to="{name:'login',query:{id:'這個是路由跳轉傳遞的參數'}}" tag="span">登錄</router-link> |<!--路由中參數傳遞--><router-link :to="{name:'regist',params:{arg:'這個是路由跳轉傳遞的參數'}}" tag="span">注冊</router-link> |<router-link :to="{name:'test',params:{arg2:'這個是路由跳轉傳遞的參數'}}" tag="span">測試</router-link> <!--routerView 是用來顯示數據的位置--><router-view></router-view> </div><script>var login={template:'<h1>登錄 {{msg}}</h1>', data(){return {msg:''};},created(){//在組件中接收路由跳轉的查詢參this.msg=this.$route.query.id;}}var regist={template:'<h1>注冊 {{arg}}</h1>',data(){return {arg:''};},created(){//在組件中接收參數this.arg=this.$route.params.arg;}}var test={template:'<h1>test {{arg2}}</h1>',//在組件中接收參數 但是在路由中要設置 props:true 才可以這樣接收props:['arg2']}//創建路由對象var routerObj=new VueRouter({//路由匹配規則routes:[{path:'/',redirect:'/login'},{path:'/login',name:'login',component:login},{path:'/regist/:arg',name:'regist',component:regist},{path:'/test/:arg2',name:'test',props:true,component:test}]}); var app=new Vue({el:'#app',data:{},methods:{},router:routerObj // 將路由規則對象,注冊到vm實例上,用來監聽url地址變化 然后用來展示對應組件});</script></body> </html>vue路由嵌套
路由跳轉問題: 當路由跳轉時,頁面path沒有改變但是傳遞參數改變了,頁面上參數沒有隨著參數的改變而改變 解決方案:<router-view :key="$route.fullPath"></router-view> <html><head><meta charset="utf-8"><title></title><script src="js/vue.js"></script><script src="vue-router.js"></script></head><body><div id="app"><router-link to="/account">賬戶</router-link><router-view></router-view></div><template id="temp"><div><router-link to="/account/login">登錄</router-link><router-link to="/account/regist">注冊</router-link><router-view></router-view></div></template><script>var login={template:'<h1>登錄</h1>',}var regist={template:'<h1>注冊</h1>',}var account={template:'#temp',}var router=new VueRouter({routes:[{path:'/account',component:account,/*為什么子路由的path前沒有/ 因為這樣會在根目錄匹配路徑*//*使用children屬性實現子路由同時path前面不要帶/*/children:[{path:'regist',component:regist},{path:'login',component:login},],}],});var app=new Vue({el:'#app',data:{},methods:{},router,});</script></body> </html>require 使用說明
在模塊化開發中,可以通過require異步加載組件(提交加載速度)
使用步驟如下
1、Load JavaScript Files 引入require.js文件
2、Define a Module 定義一個模塊
3、import Define Module 導入定義的模塊
webpack 使用說明
webpack主要用于將項目打包(html、css、js、img分別打包成想要的樣子)
1、安裝webpack和 webpack-cli
2、書寫配置文件webpack.config.js
通過npm init 命令自動創建package.json
3、進行打包測試 webpack
4、為了webpack能夠加載css文件,安裝style-loader、css-loader、sass-loader
5、在webpack.config.js中配置這三個加載css的模塊
6、打包測試
7、安裝熱部署插件(webpack-dev-server)
8、然后通過熱部署插件啟動
css 處理語言
css處理語言主要包括如下三種 less、sass、stylus他們的目的主要是為了將css的使用像js中的方法那樣可以復用
webpack引入css處理語言
也可以安裝file-loader1 url-loader 在打包時候對圖片進行base64處理
babel-loader
babel主要用于,webpack打包時候將es6轉換成es5,es6有些瀏覽器不支持
安裝
vue-cli2和vue-cli3區別
vue-cli2
使用webpack 3 進行打包、
能看到少數webpack配置
vue-cli3
使用webpack 4 進行打包、
實現webpack零配置(移除build和config文件夾)、
實現一個vue ui來管理項目插件、
移除static文件夾,使用public文件夾代替
vue腳手架 vue-cli2安裝項目
安裝前準備
1.安裝node命令行輸入node -v查詢版本號,有版本號即安裝成功 2.node自帶npm包管理工具(安裝好node也可以輸入npm -v查看版本號) npm太慢 3.下載國內淘寶鏡像cnpm (npm install -g cnpm --registry=https://registry.npm.taobao.org) 或者 修改npm的資源鏡像鏈接 npm config set registry http://registry.npm.taobao.org 4.安裝webpack 運行npm install webpack -g 或 cnpm install webpack -g 5.1安裝vue-cli 2.x npm install vue-cli -g 5.2安裝vue-cli 3.x npm install @vue/cli -g執行命令 vue init webpack vue-study 安裝項目
? Project name vue-study ? Project description 一個vue項目 ? Author lizhiyu ? Vue build standalone ? Vue build (Use arrow keys)Runtime + Compiler: recommended for most users(這個功能全,但是速度慢,初學建議使用這個)Runtime Only(這個速度快,體積小)這兩者的區別在于創建項目的main.js不同,導入模板的方式不同Runtime Only后期使用可能有些問題 ? Install vue-router? No ? Use ESLint to lint your code? Yes ? Pick an ESLint preset Standard ? Set up unit tests No ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recommended) npmpackage.json信息如下
"scripts": {"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", //通過webpack-dev-server 啟動"start": "npm run dev", //執行上面的命令"lint": "eslint --ext .js,.vue src",//測試eslint是否編譯通過"build": "node build/build.js"//通過node執行build.js},build.js主要信息如下
const webpackConfig = require('./webpack.prod.conf') //刪除上次打包好的配置 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {if (err) throw err//根據生產配置文件進行打包webpack(webpackConfig, (err, stats) => {process.stdout.write(stats.toString({colors: true,modules: false,children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.chunks: false,chunkModules: false}) + '\n\n')}) })vue腳手架 vue-cli3
vue-cli是一個腳手架工具,為我們搭建了開發所需要的環境和生成目錄架構
vue-cli 安裝和打包
npm uninstall -g vue-cli //卸載腳手架2 npm install @vue/cli -g //安裝3 創建項目:vue create 項目名(不要取中文名字) 安裝選擇如下:Please pick a preset: 選擇當前要安裝的Manually select features 手動選擇(*) Choose Vue version 選擇vue的版本,選vue2(*) Babel 用于es5和es6轉換的插件( ) TypeScript( ) Progressive Web App (PWA) Support(*) Router 路由(*) Vuex 狀態管理>(*) CSS Pre-processors css預處理(*) Linter / Formatter elsint代碼格式( ) Unit Testing( ) E2E TestingUse history mode for router? n //history精通可以使用Pick a CSS pre-processor 選Stylus,ui庫中如果使用cube-ui就要選擇個Pick a linter / formatter config: 選ESLint + Standard config,標準的格式Pick additional lint features:>(*) Lint on save 在保存時候eslint進行校驗? Where do you prefer placing config for Babel, ESLint, etc.?> In dedicated config files 將配置文件分別存放到不同目錄下啟動創建好的項目 cnpm run serve 運行項目 訪問項目 瀏覽器中訪問http://localhost:8080/ 開發項目 打包 cnpm run build 進行打包vue-cli 3.0配置
在 vue.config.js 文件中配置,每次修改配置要重啟才生效
module.exports = {publicPath: process.env.NODE_ENV === 'production' ? '/public/' : './',/* 輸出文件目錄:在npm run build時,生成文件的目錄名稱 */outputDir: 'dist',/* 放置生成的靜態資源 (js、css、img、fonts) 的 (相對于 outputDir 的) 目錄 */assetsDir: "assets",/* 是否在構建生產包時生成 sourceMap 文件,false將提高構建速度 */productionSourceMap: false,/* 默認情況下,生成的靜態資源在它們的文件名中包含了 hash 以便更好的控制緩存,你可以通過將這個選項設為 false 來關閉文件名哈希。(false的時候就是讓原來的文件名不改變) */filenameHashing: false,/* 代碼保存時進行eslint檢測 */lintOnSave: true,/* webpack-dev-server 相關配置 */devServer: {/* 自動打開瀏覽器 */open: true,/* 設置為0.0.0.0則所有的地址均能訪問 */host: '0.0.0.0',port: 8066,https: false}, }VueX
VueX能做什么
當多個組件使用同一個數據的時候,由于數據不能共享,引入vuex來解決問題
當不存在vuex時,將數據定義在父組件,通過父組件傳遞給要使用數據的子組件
結構
圖解
使用
安裝vuex
Vue 創建項目
Bable
Router 路由
Vuex 狀態管理工具
linter/Formatter 代碼提示
配置文件
在 github 上創建倉庫,然后來到項目目錄下進行推送代碼
7. 代碼開發
首先看自己所在分支 git status
創建一個分支 git branch login
切換分支 git checkout login (本地有沒有提交的代碼,則需要加 git checkout -f login 強制切換分支,這樣沒有提交的代碼會丟失)
查看分支 git branch
8. 項目啟動
在任務中運行serve 編譯成功后啟動app
main.js 是最主要的入口文件
總結
- 上一篇: 达尔优机械师合金版灯光
- 下一篇: BDBR和BD-PSNR说明