vue常用特性

1. 表單操作

表單域修飾符

  1. number:轉化爲數值
  2. trim:去掉開始和結尾的空格
  3. lazy:將input事件切換爲change事件,可以設置input失去焦點的時候觸發
 <input type="text" v-model.number="number">
 <input type="text" v-model.trim="trim">
 <input type="text" v-model.lazy="msg">

2. 自定義指令

inserted:被綁定元素插入父節點時調用
舉例:當頁面加載時,該元素將獲得焦點

// 註冊一個全局自定義指令 `v-focus`
Vue.directive('focus', {
  // 當被綁定的元素插入到 DOM 中時……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
//組件中使用
    <input v-focus>

3 . 計算屬性

3.1 使用場景

模板中放入太多的邏輯會讓模板過重且難以維護 使用計算屬性可以讓模板更加的簡潔
例子:如果要將一個字符串翻轉,在插值表達式中寫數據的處理邏輯會讓模板過重且難以維護

computed: {
      reversedMessage(){
        return this.message.split('').reverse().join('')
      }
    }
//在模板中使用
<div>    {{reversedMessage}}</div>

計算屬性與方法的區別

  • 計算屬性是基於它們的依賴進行緩存的
  • 方法不存在緩存
<div>{{reversedMessage}}</div>
    <div>{{reversedMessage}}</div>
    <div>{{reversedString()}}</div>
    <div>{{reversedString()}}</div>

methods: {
      
      reversedString(){
        console.log('method')
        return this.message.split('').reverse().join('')
      }
    },
    computed: {
      reversedMessage(){
        console.log('computed')
        return this.message.split('').reverse().join('')
      }
    }

//控制檯只打印一個computed,兩個method

4 . 偵聽器watch

4.1 偵聽器的使用場景

一般用於異步或者開銷較大的操作
watch 中的屬性 一定是data 中 已經存在的數據
Watch 中的屬性不能自定義

:<input type="text" v-model="fristname">:<input type="text" v-model="lastname">
{{fullname}}

  watch: { 
  //監聽fristname和lastname數據變化
      fristname(value) {
        this.fullname = `${value} ${this.lastname}`
      },
      lastname(value) {
        this.fullname = `${this.fristname} ${value} `
      }
    }
   

上面的列子也能用計算屬性實現

 fullname() {
        return `${this.fristname} ${this.lastname} `
      }

偵聽器處理異步的案例:輸入用戶名調用接口驗證用戶用戶名是否可用

用戶名: <span><input type="text" v-model.lazy="usename"></span><span>{{tip}}</span>

 methods: {
     
      checkName(usename) {
        //調用接口.可以用定時任務模擬接口調用
        setTimeout (()=>{
       this.tip=  usename === 'admin' ? "該用戶名已經存在" :'用戶名可以使用'
        },100)
      }
    },
 watch: {
   usename(val) {
     this.checkName(val)
     this.tip='正在驗證'
      }
    }

5 . 過濾器filter

格式化數據,比如將字符串格式化爲首字母大寫,將日期格式化爲指定的格式等
在這裏插入圖片描述

定義過濾器:
一個組件的選項中定義本地的過濾器:

filters: {
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    //首字母大寫
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}

全局定義

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  // ...
})

使用

<!-- 在雙花括號中 -->
{{ message | capitalize }}

<!--`v-bind`-->
<div v-bind:id="rawId | formatId"></div>

過濾器可以串聯:

{{ message | filterA | filterB }}

過濾器是 JavaScript 函數,因此可以接收參數:

{{ message | filterA('arg1', arg2) }}

案例:將日期格式化爲YYY-MM-DD格式

/** 
 * 對日期進行格式化, 
 * @param date 要格式化的日期 
 * @param format 進行格式化的模式字符串
 *     支持的模式字母有: 
 *     y:年, 
 *     M:年中的月份(1-12), 
 *     d:月份中的天(1-31), 
 *     h:小時(0-23), 
 *     m:分(0-59), 
 *     s:秒(0-59), 
 *     S:毫秒(0-999),
 *     q:季度(1-4)
 * @return String
 * @author yanis.wang
 * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
 */
function dateFormat(date, format) {
    if (typeof date === "string") {
        var mts = date.match(/(\/Date\((\d+)\)\/)/);
        if (mts && mts.length >= 3) {
            date = parseInt(mts[2]);
        }
    }
    date = new Date(date);
    if (!date || date.toUTCString() == "Invalid Date") {
        return "";
    }
    var map = {
        "M": date.getMonth() + 1, //月份 
        "d": date.getDate(), //日 
        "h": date.getHours(), //小時 
        "m": date.getMinutes(), //分 
        "s": date.getSeconds(), //秒 
        "q": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds() //毫秒 
    };

    format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
}

6.組件插槽

父組件向子組件傳遞內容
在這裏插入圖片描述
v-slot詳解

  1. 匿名插槽
  2. 具名插槽
  3. 作用域插槽
  • 父組件對子組件加工處理
  • 既可以複用子組件的slot,又可以使slot內容不一致
  • 使用:
    子組件模板中,元素上有一個類似props傳遞數據給組件的寫法msg="xxx.
    插槽可以提供一個默認內容,如果如果父組件沒有爲這個插槽提供了內容,會顯示默認的內容。 如果父組件爲這個插槽提供了內容,則默認的內容會被替換掉

7. axios的用法

axios官方文檔

axios主要特徵:

  • 基於promise用於瀏覽器和node.js的http客戶端
  • 支持瀏覽器和node.js
  • 能攔截請求和響應
  • 自動轉換JSON數據
  • 能轉換請求和響應數據
    使用方式
//執行get請求
// 爲給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的請求也可以這樣做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  //執行post請求
  axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  //多個並行請求
  function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 兩個請求現在都執行完成
  }));

常用API
axios(config)

// 發送 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 獲取遠端圖片
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// 發送 GET 請求(默認的方法)
axios('/user/12345');

某個請求的響應包含以下信息

{
  // `data` 由服務器提供的響應
  data: {},

  // `status` 來自服務器響應的 HTTP 狀態碼
  status: 200,

  // `statusText` 來自服務器響應的 HTTP 狀態信息
  statusText: 'OK',

  // `headers` 服務器響應的頭
  headers: {},

   // `config` 是爲請求提供的配置信息
  config: {},
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

項目中使用的例子:

getInfo() {
      console.log(666)
      axios({
        url: url.getDetailGoodsInfo,
        method: 'post',
        data: {
          goodsId: this.goodsID,
        },
      })
        .then((response) => {
          console.log(response)
          response.data.code === 200 && response.data.message
            ? (this.goodsInfo = response.data.message)
            : Toast('服務器錯誤,數據取得失敗')
          console.log(this.goodsInfo)
        })
        .catch((error) => {
          console.log(error)
        })
    },

配置默認值

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';

攔截器

  1. 請求攔截器:在請求發生之前設置一些信息
    在這裏插入圖片描述

  2. 響應攔截器:在獲取數據之前給數據做一些加工處理
    在這裏插入圖片描述

// 添加請求攔截器
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);
  });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章