Vue 2020

Vue模板語法

v-once 只編譯一次

  • 顯示內容后不再需要響應式功能

v-model 雙向綁定

  • 頁面可以同步到view層,邏輯層也可以同步到view層

v-on:click

  • @click 事件綁定

函數參數傳遞

  • 如果事件直接綁定函數名稱,那么默認會傳遞事件對象作為函數的第一個參數
  • 如果多個參數,那么事件函數必須作為最后一個

事件修飾符

  • v-on:click.stop="handle"

  • 阻止冒泡(其實就是事件不往上級(外層)傳遞)

  • v-on:click.prevent="handle"

  • 阻止默認行為

按鍵修飾符

  • .enter 回車鍵 v-on:keyup.enter='submit'

  • .delete 刪除鍵 v-on:keyup.delete='handle'

  • 簡寫

    • v-on 縮寫 @ 點擊事件
    • v-bind 縮寫 : 綁定事件 修改為動態

樣式綁定

  • 對象語法 <div :class="{active:isActive}">
  • 描述的意思就是active這個樣式受isActive這個布爾值影響是否顯示
  • 數組語法
<div :class="{active:isActive}">
.style{
    active:{
        width:200px;
    }
}

// 數組與對象結合
<div :class=['activeClass,errorClass,{active:isActive}']>
// 簡化版數組
<div :class='arrClasses']>
// 簡化版對象
<div :class='objClasses']>

data(){
    return{
        arrClasses:[active,error,other]
        objClasses:{
            active:true,
            error:true
        }
        isActive:true,
        activeClass:'active', // active 為樣式
        errorClass:'error' // error 為樣式
        
    }
}
  • style樣式處理(內鏈樣式)

    <div :style={color:active,fontSize:fontSize}>
    // 對象語法
    <div :style='objClass'>
    // 數組語法
    <div :style='[objClass,objClass2]'>
    data(){
      return{
          active:#ffffff,
          fontSize:20px,
          objClass:{
              color:#ffffff,
              fontSize:20px;
          },objClass2:{
              color:#fffeee,
              fontSize:20px;
          }
      }
    }
    
  • v-show 控制元素是否顯示 display:none/block

  • v-for 的key作用:幫組Vue區分不同的元素,從而提高性能,Vue也可以自己區分,但比較耗費性能,建議每次都加上key

    v-for='(value,key,index) in arr' // 遍歷對象
    

Vue常用屬性

  • trim 去空格 / number 數字

    <input v-model.number/trim='age'>
    <input v-model.lazy='age'> // 當失去焦點時 觸發事件 將input事件切換為change事件
    
  • 自定義指令 沒啥用

  • 計算屬性

    // 基于data里面的值并且緩存
    // computed要比method 有效率,因為它有緩存機制
    computed:{
      reverseString:function(){
          return this.msg.split('').reverse();
      }
    }
    
  • 監聽屬性

    var vm = new Vue({
      el: '#demo',
      data: {
        firstName: 'Foo',
        lastName: 'Bar',
        fullName: 'Foo Bar'
      },
      watch: {
       // 當firstName的值發生變化時調用
        firstName: function (val) {
          this.fullName = val + ' ' + this.lastName
        },
        // 當lastName的值發生變化時調用
        lastName: function (val) {
          this.fullName = this.firstName + ' ' + val
        }
      }
    })
    
  • 過濾器

    filters:{
      reverse : function(v){
          return v.reverse;
      }
    }
    

生命周期

掛載(初始化相關屬性)

  • beforeCreate
  • create
  • beforeMount
  • mounted

更新(元素或組件的變更操作) 界面更新時調用

  • beforeUpdate
  • updated

銷毀(銷毀相關屬性)

  • beforeDestroy

  • destory

  • 替換數組

    push() pop() shift() unshift() splice() sort() reverse() 影響原始數組

    filter() concat() slice() 不影響原始數組

Vue組件化

父組件向子組件傳值

  • props
Vue.component('blog-post', {
  // 在 JavaScript 中是 camelCase 的
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})

// 子組件往父組件傳遞數據
this.$emit('myEvent')


<!-- 在 HTML 中是 kebab-case 的 -->
<blog-post :myEvent="doingSomthing" post-title="hello!"></blog-post>


  • 插槽
<navigation-link url="/profile">
 hello world
</navigation-link>

Vue.component('navigation-link', {
  template: <a v-bind:href="url" class="nav-link">
                <slot></slot>//這里將使用hello world替換
            </a>
})

// 作用域插槽 應用場景:父組件對子組件的內容進行加工處理
// 子組件
<ul>
    <li v-for="item in list" :key="item.id">
        <slot :row=item>
        {{item.name}}
        </slot>
    </li>
</ul>

// 插槽內容
<future-list :list='list'>
    <template v-slot='scope'>
    {{scope.row.name}}
    </template>
</future-list>

Vue前端交互

URL地址格式

  • 傳統格式 shcema://host:port/path?query#fragment
    • schema 協議 例如 http https ftp等等
    • host 域名
    • port 端口
    • path 路徑
    • query 查詢參數
    • fragment 錨點
  • Restful形式
    • HTTP請求方式
    • get / post / put / delete

Promise用法

  • Promise是異步解決方案
//初始化
var value = new Promise(resolve,reject => {
    if(true){
        resolve("success message")
    }else {
        resolve("error message")
    }
})

// 1 回調數據
value.then(res => {
    console.log(res) // success message
},res =>{
    console.log(res) // error message
})

// 2 

value.then(res => {
    console.log(res) //
    return request()
}).then(res => {
            console.log(res)
            return 'string'
        },res =>{
            console.log(res)
            return 'error'
        })
.then(res => {
    console.log(res)// 'string'
    return request()
}).catch(res =>{
    //獲取異常信息
}).finally(res => {
    //成功與否都會執行
})

// 多個請求 并發處理多個異步任務,所有任務執行完成后才能得到結果
Promise.all([request1,request2,request3]).then(result => {
    console.log(result)
})

// 并發處理多個異步任務,只要有一個任務完成就得到結果
Promise.race([request1,request2,request3]).then(result =>{
    console.log(result)
})

fetch

  • 網絡請求
fetch(url,
    {
        method:'POST',
        headers:{
            //'Content-type':'application/x-xxx-form-urlencoded'
             'Content-type':'application/json'

        },
        body:JSON.stringfy({
            requestParam:params
        })
    }
).then(res => {
    // return data.text(); // 數據轉換為字符串
    return data.json() // 數據轉為json
}).then(res => {
    console.log(res) //真正的返回數據
})

axios

  • 網絡請求
// get請求
axios.get(url).then(res => {
    console.log(res)
})

// 三種傳參方式
axios.get(url?params='***').then(res => {
    console.log(res)
})
axios.get(url/'***').then(res => {
    console.log(res)
})
axios.get(url,{
    params:{
        params:'***'
    }
}).then(res => {
    console.log(res)
})

// post 
axios.post(url,
      {  params1:'***',
         params2:'***'
      }
).then(res => {
    console.log(res)
})

const params = ne URLSearchParams();
param.append('params1','***')
param.append('params2','***')
axios.post(url,params).then(res => {
    console.log(res)
})

// axios的全局配置
axios.defaults.timeout = 3000;
axios.defaults.headers['token'] = tokenValue

//請求攔截器
axios.interceptors.request.use(config => {
    // 請求前進行信息設置
    return config;
},res =>{
    //處理響應的錯誤信息
})


//響應攔截器
axios.interceptors.request.use(config => {
    // 請求前進行信息設置
    return config;
},res =>{
    //處理響應的錯誤信息
})
  • data 實際返回的響應數據
  • headers 響應頭信息
  • status 響應狀態碼
  • statusText 響應狀態信息

async/await用法

  • async 關鍵字用于函數上,async函數的返回值是Promise
  • await關鍵字用于async函數中,await可以得到異步的結果,后跟Promise對象

Vuex 使用

  • state 數據源

    import { mapState } from 'vuex'
    computed:{
      ...mapState(['user'])
    }
    
  • getters 獲取數據源

    import { mapGetters } from 'vuex'
    
    computed:{
      ...mapGetters(['getParams'])
    }
    
  • actions 異步操作數據

    // actions用于執行異步操作
    import { mapActions } from 'vuex'
    
    methods:{
      ...mapActions(['operation'])
    }
    
  • mutations 同步操作數據

    // 用戶變更Store中的數據 只能用mutations來修改Store中的數據
    // mutations 不能執行異步代碼
    // js代碼 第一種修改方式
    this.$store.commit('operation',params)
    
    // 第二種
    import { mapMutations } from 'vuex'
    
    methods:{
      ...mapMutations(['operation'])
    }
    
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。