1.組件
組件(component)是vue.js最強大的功能之一。組件可以擴展html元素,封裝可重用的代碼。組件系統讓我們可以用獨立可復用的小組件來構建大型應用,幾乎任意類型的應用的界面都可以抽象為一個組件樹。
1.1.注冊一個全局組件:
Vue.component(tagName, options)
tagName 為組件名,options 為配置選項。注冊后,我們可以使用以下方式來調用組件:<tagName></tagName>
prop 是父組件用來傳遞數據的一個自定義屬性。
2.事件
2.1.使用.native監聽組件上原生事件。如:
<my-component v-on:click.native="doTheThing"></my-component>
2.2.監聽事件:$on(eventName);觸發父組件的自定義事件:$emit( event, arg )
<div id="app"> <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> <button-counter v-on:increment="incrementTotal"></button-counter> </div> </div> <script> Vue.component('button-counter', { template: '<button v-on:click="incrementHandler">{{ counter }}</button>', data: function () { return { counter: 0 } }, methods: { incrementHandler: function () { this.counter += 1 this.$emit('increment') } }, }) new Vue({ el: '#counter-event-example', data: { total: 0 }, methods: { incrementTotal: function () { this.total += 1 } } }) </script>
子組件將counter加1后調用的父組件的increment點擊事件,進行兩個total加1的計算。
{}用於定義對象,如:var obj = {"id":"12","name":"jack"}. []用於聲明函數,如:var a = [1,"ad"]
例子中的data是一個函數,好處是每個實例可以維護一份被返回對象的獨立的拷貝,如果 data 是一個對象則會影響到其他實例。
3.自定義指令
除了默認設置的核心指令( v-model 和 v-show ), Vue 也允許注冊自定義指令。定義全局指令:directive 定義局部指令:directives
下面我們注冊一個全局指令 v-focus, 該指令的功能是在頁面加載時,元素獲得焦點:
<div id="app"> <p>頁面載入時,input 元素自動獲取焦點:</p> <input v-focus> </div> <script> // 注冊一個全局自定義指令 v-focus Vue.directive('focus', { // 當綁定元素插入到 DOM 中。 inserted: function (el) { // 聚焦元素 el.focus() } }) // 創建根實例 new Vue({ el: '#app' }) </script>
指令定義函數提供了幾個鈎子函數,函數有:bind/inserted/update/componentUpdated/unbind.
鈎子函數的參數有el/binding/vnode/oldVnode;其中binding是一個對象有這些屬性name/value/oldValue/expression/arg/modifiers
4.路由
通過vue.js的路由可以通過不同的url訪問不同的內容,vue.js路由需要載入vue-router庫:https://github.com/vuejs/vue-router
中文文檔地址:https://router.vuejs.org/zh/
<router-link> 是一個組件,該組件用於設置一個導航鏈接,切換不同 HTML 內容。 to 屬性為目標地址, 即要顯示的內容。
<router-link> 相關屬性有:to/replace/appead(相當於router.push()/ router.replace()/ router.appead()) tag/active-class/exact-active-class/event
5.axios
5.1.Axios 是一個基於 Promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。Github開源地址: https://github.com/axios/axios
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 請求失敗處理
console.log(error);
});
}
})
mounted,method,computed三者的區別:(轉載 https://www.jianshu.com/p/c5b1dd18eda2)
mounted : 在這發起后端請求,拿回數據,配合路由鈎子做一些事情 (dom渲染完成 組件掛載完成 )methods中一般都是定義的需要事件觸發的一些函數。每次只要觸發事件,就會執行對應的方法。如果把computed中的方法寫到method中會浪費性能。computed必須返回一個值頁面綁定的才能取得值,而methods中可以只執行邏輯代碼,可以有返回值,也可以沒有。
axios(config)
//NO.1. 發送 POST 請求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
//NO.2. 發送 GET 請求
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 請求失敗處理
console.log(error);
});
}
})
//NO.3. 直接在 URL 上添加參數 ID=12345
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// NO.4.也可以通過 params 設置參數:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// NO.5.
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response))
.catch(function (error) { // 請求失敗處理
console.log(error);
});
}
})
// NO.6.
axios.post('/user', {
firstName: 'Fred', // 參數 firstName
lastName: 'Flintstone' // 參數 lastName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
5.2.請求配置項。下面是創建請求時可用的配置選項,注意只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。
注意這是局部的請求的完整寫法,與5.1比較。
{ // `url` 是用於請求的服務器 URL url: "/user", // `method` 是創建請求時使用的方法 method: "get", // 默認是 get // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL baseURL: "https://some-domain.com/api/", // `transformRequest` 允許在向服務器發送前,修改請求數據 // 只能用在 "PUT", "POST" 和 "PATCH" 這幾個請求方法 // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被發送的自定義請求頭 headers: {"X-Requested-With": "XMLHttpRequest"}, // `params` 是即將與請求一起發送的 URL 參數 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 params: { ID: 12345 }, // `paramsSerializer` 是一個負責 `params` 序列化的函數 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: "brackets"}) }, // `data` 是作為請求主體被發送的數據 // 只適用於這些請求方法 "PUT", "POST", 和 "PATCH" // 在沒有設置 `transformRequest` 時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: "Fred" }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 如果請求花費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // 默認的 // `adapter` 允許自定義處理請求,以使測試更輕松 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: { username: "janedoe", password: "s00pers3cret" }, // `responseType` 表示服務器響應的數據類型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream" responseType: "json", // 默認的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: "XSRF-TOKEN", // default // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: "X-XSRF-TOKEN", // 默認的 // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // 默認的 }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 如果設置為0,將不會 follow 任何重定向 maxRedirects: 5, // 默認的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項: // `keepAlive` 默認沒有啟用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // "proxy" 定義代理服務器的主機名稱和端口 // `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: { host: "127.0.0.1", port: 9000, auth: : { username: "mikeymike", password: "rapunz3l" } }, // `cancelToken` 指定用於取消請求的 cancel token // (查看后面的 Cancellation 這節了解更多) cancelToken: new CancelToken(function (cancel) { }) }
響應結構:
{
// `data` 由服務器提供的響應
data: {},
// `status` HTTP 狀態碼
status: 200,
// `statusText` 來自服務器響應的 HTTP 狀態信息
statusText: "OK",
// `headers` 服務器響應的頭
headers: {},
// `config` 是為請求提供的配置信息
config: {}
}
5.3.全局配置 axios的默認值。
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
5.4.配置的優先順序。
配置會以一個優先順序進行合並。這個順序是:在 lib/defaults.js 找到的庫的默認值,然后是實例的 defaults 屬性,最后是請求的 config 參數。后者將優先於前者。
6.攔截器。// 添加請求攔截器
axios.interceptors.request.use(function (config) {
// 在發送請求之前做些什么
return config;
}, function (error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});
// 添加響應攔截器
axios.interceptors.response.use(function (response) {
// 對響應數據做點什么
return response;
}, function (error) {
// 對響應錯誤做點什么
return Promise.reject(error);
});
#method1.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
#method2.自定義 axios 實例添加攔截器。
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
# mthod1.使用 CancelToken.source 工廠方法創建 cancel token
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 處理錯誤
}
});
// 取消請求(message 參數是可選的)
source.cancel('Operation canceled by the user.');
# mthod2.可以通過傳遞一個 executor 函數到 CancelToken 的構造函數來創建 cancel token:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函數接收一個 cancel 函數作為參數
cancel = c;
})
});
// 取消請求
cancel();
headers: { 'content-type': 'application/x-www-form-urlencoded' },