日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vue 刷课笔记

發(fā)布時間:2023/12/14 vue 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue 刷课笔记 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Vue 筆記

Vue 官方文檔

什么是Vue?

  • Vue 是一套用于構(gòu)建用戶界面的漸進式JavaScript框架。
  • Vue 被設(shè)計為可以自底向上逐層應(yīng)用。
  • Vue 的核心庫只關(guān)注視圖層,方便與第三方庫或既有項目整合。
  • Vue 完全有能力驅(qū)動采用單文件組件和Vue生態(tài)系統(tǒng)支持的庫開發(fā)的復雜單頁應(yīng)用。
  • Vue綜合了 Angular(模塊化)和 React(虛擬DOM)的優(yōu)點。

Vue MVVM 模式實現(xiàn)者

  • Model: 模型層,在這里表示JavaScript對象
  • View: 視圖層,在這里表示DOM (HTML 操作的元素)
  • ViewModel: 連接視圖和數(shù)據(jù)的中間件,Vue.js 就是 MVVM 中的ViewModel層的實現(xiàn)者

在MVVM架構(gòu)中,是不允許數(shù)據(jù)和視圖直接通信的,只能通過ViewModel來通信,而ViewModel就是定義了一個 Observer 觀察者

  • ViewModel能夠觀察到數(shù)據(jù)的變化,并對視圖對應(yīng)的內(nèi)容進行更新
  • ViewModel能夠監(jiān)聽到視圖的變化,并能夠通知數(shù)據(jù)發(fā)生改變

至此,我們就明白了,Vue.js 就是一個 MVVM的實現(xiàn)者,他的核心就是實現(xiàn)了DOM監(jiān)聽與數(shù)據(jù)綁定

其它

網(wǎng)絡(luò)通信:axios(前端的通信框架)
頁面跳轉(zhuǎn):vue-router
狀態(tài)管理:vuex
Vue-UI: ICE

前端三要素:結(jié)構(gòu)層(HTML)、 表現(xiàn)層(CSS)、行為層(JavaScript)

JavaScript 構(gòu)建工具

webpack ( 模塊打包器,主要作用是打包、壓縮、合并及按序加載 )

UI 框架

Ant-Design ( 阿里巴巴出品,基于React的框 )
Element UI ( 餓了么出品,基于Vue的UI框架 ) ( 桌面端支持較多 )
Bootstrap ( Twitter 推出的用于前端開發(fā)的開源工具包 )
Amaze ~ 妹子 UI ( 中國首個開源 HTML5 跨屏前端框架 )
iView (View UI,即原先的 iView,是一套基于 Vue.js 的開源 UI 組件庫,主要服務(wù)于 PC 界面的中后臺產(chǎn)品。) ( 移動端支持比較多 )

vue-element-admin

github 官網(wǎng) ( 翻墻 )
gitee 官網(wǎng)

vue-element-admin 是一個后臺前端解決方案,它基于 vue 和 element-ui 實現(xiàn)。

一、第一個Vue程序

【說明】 IDEA 安裝 Vue 插件!

第一個Vue程序:

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><!-- View層 --> <div id="app">{{message}} </div><!-- 1.導入Vue.js --> <!-- 開發(fā)環(huán)境版本,包含了有幫助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>let vm = new Vue({el: "#app",// Model : 數(shù)據(jù)data: {message: "Hello Vue~"}}); </script></body> </html>

測試:在控制臺輸入 vm.message = “Hello World!”,顯示的內(nèi)容會改變?yōu)?#34;Hello World!"。

此時就可以在控制臺直接輸入vm.message來修改值,中間是可以省略data的,
在這個操作中,我并沒有主動操作DOM,就讓頁面的內(nèi)容發(fā)生了變化,這就是借助了Vue的數(shù)據(jù)綁定功能實現(xiàn)的;
MVVM模式中要求ViewModel層就是使用觀察者模式來實現(xiàn)數(shù)據(jù)的監(jiān)聽與綁定,以做到數(shù)據(jù)與視圖的快速響應(yīng)。

二、Vue基本語法

v-bind attribute 被稱為指令。指令帶有前綴 v-,以表示它們是 Vue 提供的特殊 attribute。
它們會在渲染的 DOM 上應(yīng)用特殊的響應(yīng)式行為。在這里,該指令的意思是:“將這個元素節(jié)點的 title attribute 和 Vue 實例的 message property 保持一致”。

<span v-bind:title="message"> 鼠標懸停幾秒鐘查看此處動態(tài)綁定的提示信息! </span>

條件與循環(huán)

  • v-if
<!-- View層 --> <div id="app"><h1 v-if="ok">Yes</h1><h1 v-else>No</h1><h1 v-if="type === 'A'">A</h1><h1 v-else-if="typr === 'B'">B</h1><h1 v-else="type === 'c'">C</h1> </div><!-- 1.導入Vue.js --> <!-- 開發(fā)環(huán)境版本,包含了有幫助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>let vm = new Vue({el: "#app",// Model : 數(shù)據(jù)data: {ok: true,type: 'A'}}); </script>
  • v-for
<!-- View層 --> <div id="app"><li v-for="item in items">{{item.message}}</li><li v-for="(item, index) in items">{{index}} --> {{item.message}}</li> </div><!-- 1.導入Vue.js --> <!-- 開發(fā)環(huán)境版本,包含了有幫助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>let vm = new Vue({el: "#app",// Model : 數(shù)據(jù)data: {items: [{message: "從入門到放棄"},{message: "從刪庫到跑路"},{message: "有手就行"}]}}); </script>

綁定事件

可以用 v-on 指令監(jiān)聽 DOM 事件,并在觸發(fā)時運行一些 JavaScript 代碼。

<!-- View層 --> <div id="app"><button v-on:click="sayHi">點擊我</button> </div><!-- 1.導入Vue.js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>let vm = new Vue({el: "#app",data: {message: "Hello World! 程序員"},methods: { // 方法必須定義在Vue 的 methods 對象中sayHi: function () {alert(this.message);}}}); </script>

三、 雙向綁定、組件

什么是數(shù)據(jù)雙向綁定?

Vue.js是一個 MVVM框架,即數(shù)據(jù)雙向綁定,即當數(shù)據(jù)發(fā)生變化的時候,視圖也就發(fā)生變化,當視圖發(fā)生變化的時候,數(shù)據(jù)也會跟著同步變化。這也算是Vue.js 的精髓之處了。

在表單中使用數(shù)據(jù)雙向綁定

你可以用 v-model 指令在表單<input>、 <textarea>及<select>元素上創(chuàng)建雙向數(shù)據(jù)綁定。
它會根據(jù)控件類型自動選取正確的方法來更新元素。盡管有些神奇,但 v-model 本質(zhì)上不過是語法糖。
它負責監(jiān)聽用戶的輸入事件以更新數(shù)據(jù),并對一些極端場景進行一些特殊處理。

注意: v-model 會忽略所有表單元素的 value、checked、selected 特性的初始值而總是將Vue實例的數(shù)據(jù)作為數(shù)據(jù)來源。你應(yīng)該通過JavaScript在組件的data選項中聲明初始值!

<!-- View層 --> <div id="app"><!-- 輸入框 --><div>輸入的文本:<input type="text" v-model="message"> {{message}}</div><!-- 單選框 --><div> 性別:<input type="radio" name="sex" value="" v-model="sex"><input type="radio" name="sex" value="" v-model="sex"><p>選中了誰: {{sex}}</p></div><!-- 下拉框 --><div>下拉框:<select v-model="selected"><option value="" disabled>--請選擇--</option><option>A</option><option>B</option><option>C</option></select><p>選中了誰: {{selected}}</p></div> </div><!-- 1.導入Vue.js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>let vm = new Vue({el: "#app",data: {message: "...",checked: false,sex: "",selected: ''},}); </script>

Vue 組件

prop 是你可以在組件上注冊的一些自定義 attribute。

當一個值傳遞給一個 prop attribute 的時候,它就變成了那個組件實例的一個 property。
為了給博文組件傳遞一個標題,我們可以用一個 props 選項將其包含在該組件可接受的 prop 列表中:

Vue.component('blog-post', {props: ['title'],template: '<h3>{{ title }}</h3>' })

一個組件默認可以擁有任意數(shù)量的 prop,任何值都可以傳遞給任何 prop。
在上述模板中,你會發(fā)現(xiàn)我們能夠在組件實例中訪問這個值,就像訪問 data 中的值一樣。

一個 prop 被注冊之后,你就可以像這樣把數(shù)據(jù)作為一個自定義 attribute 傳遞進來:

<blog-post title="My journey with Vue"></blog-post>

測試代碼:

<!-- View層 --> <div id="app"><!-- 組件:傳遞給組件中的值:props (理解:mianbao是形參,item是實參)--><my-component v-for="item in items" v-bind:mianbao="item"></my-component> </div><!-- 1.導入Vue.js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>// 定義一個Vue 的組件 componentVue.component('my-component', {props: ['mianbao'],template: '<li>{{mianbao}}</li>'});let vm = new Vue({el: "#app",data: {items: ["Java", "Mysql", "Spring"]}}); </script>

四、 Axios異步通信

什么是 axios?

Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
特性:

  • 從瀏覽器中創(chuàng)建 XMLHttpRequests
  • 從 node.js 創(chuàng)建 http 請求
  • 支持 Promise API
  • 攔截請求和響應(yīng)
  • 轉(zhuǎn)換請求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  • 取消請求
  • 自動轉(zhuǎn)換 JSON 數(shù)據(jù)
  • 客戶端支持防御 XSRF

Axios 官網(wǎng)
Axios Github

為什么要使用Axios?

由于Vue.js 是一個視圖層框架并且作者(尤雨溪)嚴格準守SoC (關(guān)注度分離原則),所以Vue.js 并不包含AJAX的通信功能,為了解決通信問題,作者單獨開發(fā)了一個名為vue-resource的插件,不過在進入2.0版本以后停止了對該插件的維護并推薦了Axios框架。少用jQuery,因為它操作Dom太頻繁!

第一個 Axios 程序

每個 Vue 實例在被創(chuàng)建時都要經(jīng)過一系列的初始化過程——例如,需要設(shè)置數(shù)據(jù)監(jiān)聽、編譯模板、將實例掛載到 DOM 并在數(shù)據(jù)變化時更新 DOM 等。
同時在這個過程中也會運行一些叫做生命周期鉤子的函數(shù),這給了用戶在不同階段添加自己的代碼的機會。

測試:
json例子:

{"name":"面包學java","url": "http://baidu.com","page": "1","isNonProfit":"true","address": {"street": "破漏山村","city":"廣西百色","country": "中國"},"links": [{"name": "B站","url": "https://www.bilibili.com/"},{"name": "4399","url": "https://www.4399.com/"},{"name": "百度","url": "https://www.baidu.com/"}] } <div id="vue"><div>{{info.address}}</div><a v-bind:href="info.url">點我</a> </div> <!-- 引入 JS 文件 --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script type="text/javascript">let vm = new Vue({el: "#vue",data() {return {// 請求的返回參數(shù)格式,必須和json字符串一樣info: {name: null,address: {country: null,city: null,street: null},url: null}}},mounted() { // 鉤子函數(shù) ES6新特性axios.get('../data.json').then(response => (this.info = response.data));}}); </script>

五、 計算屬性

var vm = new Vue({el: '#example',data: {message: 'Hello'},computed: {// 計算屬性的 getterreversedMessage: function () {// `this` 指向 vm 實例return this.message.split('').reverse().join('')}} })

我們可以將同一函數(shù)定義為一個方法而不是一個計算屬性。兩種方式的最終結(jié)果確實是完全相同的。然而,不同的是計算屬性是基于它們的響應(yīng)式依賴進行緩存的。只在相關(guān)響應(yīng)式依賴發(fā)生改變時它們才會重新求值。這就意味著只要 message 還沒有發(fā)生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結(jié)果,而不必再次執(zhí)行函數(shù)。

這也同樣意味著下面的計算屬性將不再更新,因為 Date.now() 不是響應(yīng)式依賴:

computed: {now: function () {return Date.now()} }

可以理解為緩存

六、 slot插槽

具名插槽

官網(wǎng)例子:

<div class="container"><header><!-- 我們希望把頁頭放這里 --></header><main><!-- 我們希望把主要內(nèi)容放這里 --></main><footer><!-- 我們希望把頁腳放這里 --></footer> </div>

對于這樣的情況, 元素有一個特殊的 attribute:name。這個 attribute 可以用來定義額外的插槽:

<div class="container"><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer> </div>

一個不帶 name 的 出口會帶有隱含的名字“default”。
在向具名插槽提供內(nèi)容的時候,我們可以在一個 元素上使用 v-slot 指令,并以 v-slot 的參數(shù)的形式提供其名稱:

<base-layout><template v-slot:header><h1>Here might be a page title</h1></template><template v-slot:default><p>A paragraph for the main content.</p><p>And another one.</p></template><template v-slot:footer><p>Here's some contact info</p></template> </base-layout>

自己測試代碼:

<!-- View層 --> <div id="app"><!-- 實現(xiàn)的列表 --><p>列表書籍</p><ul><li>Java</li><li>Mysql</li><li>Spring</li></ul><!-- 插槽實現(xiàn) --><todo><todo-title slot="todo-title" v-bind:title="title"></todo-title><todo-items slot="todo-items" v-for="item in todoItems" :items="item"></todo-items></todo> </div><!-- 1.導入Vue.js --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>// slot 插槽Vue.component("todo", {template:"<div>\<slot name='todo-title'></slot>\<ul>\<slot name='todo-items'></slot>\</ul>\</div>"});Vue.component("todo-title", {props: ['title'],template: '<div>{{title}}</div>'});Vue.component("todo-items", {props: ['items'],template: '<li>{{items}}</li>'});let vm = new Vue({el: "#app",// Model : 數(shù)據(jù)data: {title: "面包列表",todoItems: ['Java', 'Mysql', 'Vue']}}); </script>

七、 自定義事件內(nèi)容分發(fā)(待加深理解)


彈幕提示(拿過來理解):
bind: 綁定前端與vue的數(shù)據(jù)。props: 綁定前端與組件的數(shù)據(jù)。
this.$emit 將事件分發(fā)回前端,前端 v–on:remove 再將事件給 removeItems(處理)

測試案例:

<!-- View層 --> <div id="app"><todo><todo-title slot="todo-title" v-bind:title="title"></todo-title><todo-items slot="todo-items" v-for="(item, index) in todoItems" :items="item" v-bind:index="index" v-on:remove="removeItem(index)"></todo-items></todo> </div><!-- 1.導入Vue.js --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script>// slot 插槽Vue.component("todo", {template:"<div>\<slot name='todo-title'></slot>\<ul>\<slot name='todo-items'></slot>\</ul>\</div>"});Vue.component("todo-title", {props: ['title'],template: '<div>{{title}}</div>'});Vue.component("todo-items", {props: ['items', 'index'],template: ' <li>{{index}} ===> {{items}} <button @click="remove">刪除</button></li>',// 只能綁定當前組件的方法methods: {remove: function (index) {// this.$emit 自定義事件this.$emit("remove", index);}}});let vm = new Vue({el: "#app",// Model : 數(shù)據(jù)data: {title: "面包列表",todoItems: ['Java', 'Mysql', 'Vue']},methods: {removeItem: function (index) {console.log("刪除了"+ this.todoItems[index] + "OK");this.todoItems.splice(index, 1); // 一次刪除一個元素}}}); </script>

第一個 Vue-cli 項目

Vue CLI 是一個基于 Vue.js 進行快速開發(fā)的完整系統(tǒng)。用于生成一個 Vue 項目模板。好比在創(chuàng)建 Maven 項目時可以選擇一個骨架。
Vue CLI 提供:

  • 通過 @vue/cli 實現(xiàn)的交互式的項目腳手架。
  • 通過 @vue/cli + @vue/cli-service-global 實現(xiàn)的零配置原型開發(fā)。
  • 一個運行時依賴 (@vue/cli-service),該依賴:
  • 可升級;
  • 基于 webpack 構(gòu)建,并帶有合理的默認配置;
  • 可以通過項目內(nèi)的配置文件進行配置;
  • 可以通過插件進行擴展。
  • 一個豐富的官方插件集合,集成了前端生態(tài)中最好的工具。
  • 一套完全圖形化的創(chuàng)建和管理 Vue.js 項目的用戶界面。

1. 需要的環(huán)境

Node.js: https://nodejs.org/zh-cn/

Git : https://git-scm.com/downloads

node.js下載后無腦安裝, 確認nodejs安裝成功:

  • cmd 下輸入node -v ,查看是否能夠正確打印出版本號即可!.
  • cmd 下輸入npm-v ,查看是否能夠正確打印出版本號即可!

這個npm,就是一個軟件包管理工具,就和 linux 下的 apt 軟件安裝差不多!

安裝 Node.js 淘寶鏡像加速器 ( cnpm )
這樣子下載會快很多~

# -g 就是全局安裝 npm install cnpm -g# 或者使用如下語句解決 npm 速度慢的問題 npm install --registry=https://registry.npm.taobao.org

安裝位置:
C:\Users\17521\AppData\Roaming\npm

安裝 Vue-cli

cnpm install vue-cli -g# 測試是否安裝成功 # 查看可以基于哪些模板創(chuàng)建 vue 應(yīng)用程序,通常我們選擇 webpack vue list

2. 新建 vue-cli 程序

2.1 創(chuàng)建一個基于 webpack 模板的 vue 程序(自己選擇項目路徑)

# myvue 為項目名 vue init webpack myvue

一路都選擇 no

說明:

  • Project name: 項目名稱,默認回車即可
  • Project description: 項目描述,默認回車即可
  • Author: 項目作者,默認回車即可
  • Install vue-router: 是否安裝
    • vue-router,選擇n不安裝(后期需要再手動添加 )
  • Use ESLint to lint your code: 是否使用 ESLint 做代碼檢查,選擇n不安裝(后期需要再手動添加)
  • Set up unit tests: 單元測試相關(guān),選擇n不安裝(后期需要再手動添加)
  • Setup e2e tests with Nightwatch: 單元測試相關(guān),選擇n不安裝(后期需要再手動添加)
  • Should we run npm install for you after the project has been created: 創(chuàng)建完成后直接初始化,選擇n,我們手動執(zhí)行;
    運行結(jié)果!

2.2 初始化并運行

cd myvue npm install # 根據(jù)項目下的 package.json 安裝依賴 安裝到項目 node_modules 目錄 npm run dev

安裝依賴如果有錯誤,vue會提示,例如:

found 17 vulnerabilities (3 low, 8 moderate, 6 high)run `npm audit fix` to fix them, or `npm audit` for details

webpack 學習使用

本質(zhì)上,webpack 是一個現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊打包器(module bundler)。
當 webpack 處理應(yīng)用程序時,它會遞歸地構(gòu)建一個依賴關(guān)系圖(dependency graph),其中包含應(yīng)用程序需要的每個模塊,然后將所有這些模塊打包成一個或多個 bundle。

安裝 webpack

安裝命令:

npm install webpack -g npm install webpack-cli -g

測試安裝成功命令:

webpack -v webpack-cli -v

配置

創(chuàng)建webpack .config.js配置文件

  • entry: 入口文件,指定WebPack 用哪個文件作為項目的入口.
  • output: 輸出,指定WebPack 把處理完成的文件放置到指定路徑
  • module: 模塊,用于處理各種類型的文件
  • plugins: 插件,如:熱更新、代碼重用等
  • resolve: 設(shè)置路徑指向
  • watch: 監(jiān)聽,用于設(shè)置文件改動后直接打包

使用 webpack

1、 創(chuàng)建項目
新建文件夾:webpack-study ;然后用IDEA打開
2、 新建 modules 文件目錄,用于放置 JS 模塊等資源文件
3、 在 modules 目錄中新建 hello.js 文件和 main.js 文件

hello.js

// 暴露一個方法 exports.sayHi = function () {document.write("<h1>面包學JAVA</h1>"); };

main.js

// require:導入一個模塊就可以調(diào)用這個模塊下的方法了 let hello = require("./hello"); hello.sayHi();

4、 項目目錄下新建 webpack.config.js 文件

module.exports = {entry: './modules/main.js',output: {filename: "./js/bundle.js"} };

5、 在 IDEA 的 Terminal 中輸入命令: webpack. (管理員運行IDEA)
可以看到項目中生成 dist/js/bundle.js 文件

6、 新建 index.html 使用打包后的 bundle.js 文件, 打開瀏覽器查看效果。

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><!-- 前端的模塊化開發(fā) --> <script src="dist/js/bundle.js"></script> </body> </html>

vue-router 路由

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,讓構(gòu)建單頁面應(yīng)用變得易如反掌。包含的功能有:

  • 嵌套的路由/視圖表
  • 模塊化的、基于組件的路由配置
  • 路由參數(shù)、查詢、通配符
  • 基于 Vue.js 過渡系統(tǒng)的視圖過渡效果
  • 細粒度的導航控制
  • 帶有自動激活的 CSS class 的鏈接
  • HTML5 歷史模式或 hash 模式,在 IE9 中自動降級
  • 自定義的滾動條行為

安裝

基于第一個 vue-cli 進行測試學習;先查看 node_modules 中是否存在 vue-router
vue-router 是一個插件包,所以我們還是需要用npm/cnpm來進行安裝的。
打開命令行工具,進入你的項目目錄,輸入下面命令。

npm install vue-router --save-dev

如果要在一個模塊化工程中使用它,必須要通過 Vue.use() 明確的安裝路由

import VueRouter from "vue-router"; // 顯示聲明使用VueRouter Vue.use(VueRouter);

測試

1、 在 components 目錄下新建兩個組件
Content.vue

<template><h1>內(nèi)容頁</h1> </template><script>export default {name: "Content"} </script><style scoped></style>

Main.vue

<template><h1>首頁</h1> </template><script>export default {name: "Main"} </script><style scoped></style>

2、 src 目錄下新建一個 router 目錄,專門存放路由
創(chuàng)建并編寫 index.js

// 路由配置文件 import Vue from 'vue' import VueRouter from 'vue-router'import Content from "../components/Content"; import Main from "../components/Main";// 安裝路由 Vue.use(VueRouter);// 配置導出路由 export default new VueRouter({routes: [{// 路由路徑path: '/content',// 路由的名字name: 'content',// 跳轉(zhuǎn)的組件component: Content},{// 路由路徑path: '/main',// 路由的名字name: 'main',// 跳轉(zhuǎn)的組件component: Main}] })

3、 在 main.js 中配置

import Vue from 'vue' import App from './App'import router from './router' // 自動掃描里面的路由配置Vue.config.productionTip = false/* eslint-disable no-new */ new Vue({el: '#app',// 配置路由router,components: { App },template: '<App/>' })

4、 在 APP.vue 中使用

<template><div id="app"><h1>Vue-router</h1><router-link to="./main">首頁</router-link><router-link to="./content">內(nèi)容頁</router-link><router-view></router-view></div> </template><script>export default {name: 'App' } </script><style> .... </style>

vue + elementUI

以管理員的身份運行 cmd

1、 創(chuàng)建工程 hello-vue : vue init webpack hello-vue
2、 安裝依賴

# 進入工程目錄 cd hello-vue # 安裝 vue-router npm install vue-router --save-dev # 安裝 element ui ; https://element.eleme.cn/#/zh-CN/component/installation npm i element-ui -S # 安裝所有的依賴 npm install # 安裝 SASS 加載器 cnpm install sass-loader node-sass --save-dev # 啟動測試 npm run dev

3、 npm 命令解釋

  • npm install moduleName:安裝模塊到項目目錄下
  • npm install -g moduleName: -g 的意思是將模塊安裝到全局,具體安裝到磁盤哪個位置,要看 npm config prefix 的位置
  • npm install -save moduleName: --save 的意思是將模塊安裝到項目目錄下,并在package 文件的 dependencies 節(jié)點寫入依賴,-S 為該命令的縮寫
  • npm install -save-dev moduleName: --save-dev 的意思是將模塊安裝到項目目錄下,并在 package 文件的 devDependencies 節(jié)點寫入依賴,-D 為該命令的縮寫

4、 用 IDEA 打開工程
5、 在 src 下創(chuàng)建 view 目錄,新建 Login.vue 和 Main.vue :
Login.vue

<template><div><el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box"><h3 class="login-title">歡迎登錄</h3><el-form-item label="賬號" prop="username"><el-input type="text" placeholder="請輸入賬號" v-model="form.username"/></el-form-item><el-form-item label="密碼" prop="password"><el-input type="password" placeholder="請輸入密碼" v-model="form.password"/></el-form-item><el-form-item><el-button type="primary" v-on:click="onSubmit('loginForm')">登錄</el-button></el-form-item></el-form><el-dialogtitle="溫馨提示":visible.sync="dialogVisible"width="30%":before-close="handleClose"><span>請輸入賬號和密碼</span><span slot="footer" class="dialog-footer"><el-button type="primary" @click="dialogVisible = false">確 定</el-button></span></el-dialog></div> </template><script>export default {name:"Login",data(){return {form:{username: '',password: ''},//表單驗證,需要再el-form-item 元素中增加prop屬性rules:{username:[{required:true,message:'賬號不能為空',trigger:'blur'}],password:[{required: true,message: '密碼不能為空',trigger:'blur'}]},//對話框顯示和隱藏dialogVisible:false}},methods:{onSubmit(formName) {//為表單綁定驗證功能this.$refs[formName].validate((valid) =>{if (valid){//使用 vue-router路由到指定頁面,該方式稱之為編程式導航this.$router.push("/main");} else {this.dialogVisible = true;return false;}});},handleClose: function () {console.log("Handle Close,空函數(shù)");}}} </script><style lang="scss" scoped>.login-box{border: 1px solid #DCDFE6;width: 350px;margin:180px auto;padding:35px 35px 15px 35px;border-radius: 5px;-webkit-border-radius: 5px;-moz-border-radius: 5px;box-shadow:0 0 25px #909399;}.login-title{text-align:center;margin:0 auto 40px auto;color:#303133;}.login-box{border: 1px solid #DCDFE6;width: 350px;margin:180px auto;padding:35px 35px 15px 35px;border-radius: 5px;-webkit-border-radius: 5px;-moz-border-radius: 5px;box-shadow:0 0 25px #909399;}.login-title{text-align:center;margin:0 auto 40px auto;color:#303133;} </style>

Main.vue

<template><h1>首頁</h1> </template><script>export default {name: "Main"} </script><style scoped></style>

6、 在 src 下創(chuàng)建 router 目錄,新建 index.js:

import Vue from 'vue'; import VueRouter from "vue-router"; import Login from "../view/Login"; import Main from "../view/Main";Vue.use(VueRouter);export default new VueRouter({routes: [{path: '/main',component: Main},{path: '/login',component: Login}] })

7、 main.js 配置

import Vue from 'vue' import App from './App'// 路由 import router from './router'// 引入 Element UI import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css';Vue.use(router); Vue.use(ElementUI);Vue.config.productionTip = false;/* eslint-disable no-new */ new Vue({el: '#app',router,render: h => h(App) // Element UI });

8、 App.vue 添加代碼: router-view 標簽展示路由頁面

<template><div id="app"><router-view></router-view></div> </template>

9、 運行 npm run dev

  • 如果出錯,在 package.json 降低 “sass-loader” 的版本為 ^7.3.1

  • 再次運行報錯:Error:Node Sass version 5.0.0 is incompatible with ^4.0.0: 在 package.json 降低 “node-sass” 的版本為 ^4.14.1

    工程目錄

嵌套路由

1、 編寫 Main.vue

<template><el-container><!-- 側(cè)邊欄 --><el-aside width="200px"><el-menu :default-openeds="['1']"><el-submenu index="1"><template slot="title"><i class="el-icon-caret-right"></i>用戶管理</template><el-menu-item-group><el-menu-item index="1-1"><router-link to="/user/profile">個人信息</router-link></el-menu-item><el-menu-item index="1-2"><router-link to="/user/list">用戶列表</router-link></el-menu-item></el-menu-item-group></el-submenu><el-submenu index="2"><template slot="title"><i class="el-icon-caret-right"></i>內(nèi)容管理</template><el-menu-item-group><el-menu-item index="2-1">分類管理</el-menu-item><el-menu-item index="2-2">內(nèi)容列表</el-menu-item></el-menu-item-group></el-submenu></el-menu></el-aside><el-container><!-- 頭部 --><el-header style="text-align: right; font-size: 12px"><el-dropdown><i class="el-icon-setting" style="margin-right:15px"></i><el-dropdown-menu slot="dropdown"><el-dropdown-item>個人信息</el-dropdown-item><el-dropdown-item>退出登錄</el-dropdown-item></el-dropdown-menu></el-dropdown></el-header><el-main><router-view></router-view></el-main></el-container></el-container> </template><script>export default {name: "Main"} </script><style scoped lang="scss">.el-header {background-color: #048bd1;color: #333;line-height: 60px;}.el-aside {color: #333;} </style>

2、 在 view 目錄下新建 user 目錄, 新建 List.vue 和 Profile.vue

<template><h1>用戶列表</h1> </template><script>export default {name: "UserList"} </script><style scoped></style> <template><h1>個人信息</h1> </template><script>export default {name: "UserProfile"} </script><style scoped></style>

3、 在 router 的 index.js 中配置

...routes: [{path: '/main',component: Main,// 嵌套路由children: [{ path: '/user/profile', component: UserProfile },{ path: '/user/list', component: UserList }]}, ...

4、 運行并測試

參數(shù)傳遞及重定向

修改 Main.vue

...<!-- name: 組件名字 params: 參數(shù) 需要對象:v-bind --><router-link :to="{name: 'UserProfile', params: {id: 1}}">個人信息</router-link> ...

路由配置 index.js

...children: [{ path: '/user/profile/:id', name: 'UserProfile', component: UserProfile }, ...

修改 Profile.vue

<template><!-- 所有的元素,不能直接在根節(jié)點下 --><div><h1>個人信息</h1>{{ $route.params.id }}</div> </template>

測試

通過 props 解耦

開啟 props: true

...children: [{ path: '/user/profile/:id', name: 'UserProfile', component: UserProfile, props: true }, ...

Main.vue 不變, 修改 Profile.vue : 增加 props: [‘id’], 就可以直接使用 {{id}}

<template><!-- 所有的元素,不能直接在根節(jié)點下 --><div><h1>個人信息</h1> <!-- {{ $route.params.id }}-->{{id}}</div> </template><script>export default {props: ['id'],name: "UserProfile"} </script>

重定向

...{path: "/goHome",redirect: '/main'}

路由鉤子和404

路由模式

路由模式有兩種:

  • hash : 路徑帶 # 符號。 如: http://localhost:8080/#/login
  • history: 路徑不帶 # 符號。 如:http://localhost:8080/login

修改路由配置:

export default new VueRouter({mode: 'history',routes: [...

404

處理 404 創(chuàng)建一個名為 NotFound.vue 的視圖,代碼如下:

<template><div><h1>404, 你找的頁面走丟了...</h1></div> </template><script>export default {name: "NotFound"} </script><style scoped></style>

路由配置 index.js

import NotFound from "../view/NotFound"; ...{path: '*',component: NotFound}

路由鉤子

  • beforeRouteEnter:在進入路由之前執(zhí)行
  • beforeRouteLeave:在離開路由之前執(zhí)行
<script>export default {props: ['id'],name: "UserProfile",// 攔截器 request->to, response->form, chain->nextbeforeRouteEnter: (to, from, next) => {console.log("進入路由之前");next();},beforeRouteLeave: (to, from, next) => {console.log("離開路由之后");next();}} </script>

參數(shù)說明:

  • to:路由將要跳轉(zhuǎn)的路徑信息
  • from:路徑跳轉(zhuǎn)前的路徑信息
  • next:路由的控制參數(shù)
    • next()跳入下一個頁面
    • next(’/path’)改變路由的跳轉(zhuǎn)方向,使其跳到另一個路由
    • next(false)返回原來的頁面
    • next((vm)=>))僅在 beforeRouteEnter中可用,vm是組件實例

在鉤子函數(shù)中使用功一步請求

1、 安裝 Axios npm install axios -s
2、 在 main.js 中引用 Axios

// Axios import axios from 'axios'; import VueAxios from 'vue-axios';Vue.use(VueAxios, axios);

3、 在 static 新建 mock 目錄,并編寫data.json

{"name":"面包學java","url": "http://baidu.com","page": "1","isNonProfit":"true","address": {"street": "破漏山村","city":"廣西百色","country": "中國"},"links": [{"name": "B站","url": "https://www.bilibili.com/"},{"name": "4399","url": "https://www.4399.com/"},{"name": "百度","url": "https://www.baidu.com/"}] }

4、 編寫路由鉤子函數(shù)

<script>export default {props: ['id'],name: "UserProfile",// 攔截器 request->to, response->form, chain->nextbeforeRouteEnter: (to, from, next) => {console.log("進入路由之前");// 加載數(shù)據(jù)next(vm => {vm.getData(); // 進入路由之前執(zhí)行 getData()});},beforeRouteLeave: (to, from, next) => {console.log("離開路由之后");next();},methods: {getData: function () {this.axios({method: "GET",url: 'http://localhost:8080/static/mock/data.json',}).then(function (res) {console.log(res);});}}} </script>

5、 運行測試,查看控制臺輸出

總結(jié)

以上是生活随笔為你收集整理的Vue 刷课笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。