Vue 2020

作者: 云木杉 | 来源:发表于2020-05-29 18:26 被阅读0次

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'])
    }
    

相关文章

网友评论

      本文标题:Vue 2020

      本文链接:https://www.haomeiwen.com/subject/rkyfzhtx.html