Vue3中常用的Composition API

1.setup

1.1理解:Vue3.0中的一个新的配置项,值为一个函数。

1.2.setup是所有Composition API(组合API)“表演舞台”。

1.3.组件中所用到的:数据、方法等等,均要配置在setup中。

1.4.setup函数的两种返回值:

        1.若返回一个对象,则对象中的属性、方法,在模板中均可以直接使用。

        2.若返回一个渲染函数:则可以自定义渲染内容。

1.5.注意点:

        1.尽量不要与Vue2.x配置混用

                1.Vue2.x配置(data、methos、computed......)中可以访问setup中的属性、方法。

                2.但在setup中不能访问到Vue2.x配置(data、methos、computed......)

                3.如果有重名,setup优先

        2.setup不能是一个async函数,因为返回值不再是return的对象,而是promlse,模板看不到return对象中的属性。

<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{name}}</h2>
  <h2>年龄:{{age}}</h2>
  <h2>性别:{{sex}}</h2>
  <h2>x的值:{{x}}</h2>
  <button @click="sayHello">说话(vue3)</button>
  <button @click="sayWelcom">欢迎词(vue2)</button>
</template>

<script>
import {h} from 'vue'

export default {
  name: 'App',
  data () {
    return{
      sex:'男',
      x:200
    }
  },
  methods:{
    sayWelcom(){
      alert('欢迎学习vue3')
    }
  },
  //此处只是测试setup
  setup(){
    //数据
    let name = '李四'
    let age = 20
    let x = 500

    //方法
    function sayHello(){
      alert(`我叫${name},我${age}岁了,你好啊!`)
    }

    //返回一个对象
    return{
      name,
      age,
      sayHello,
      x
    }

    //返回一个渲染函数
    // return ()=>h('h1','你好啊')
  }
}
</script>

<style>
</style>

2.ref函数

2.1.作用:定义一个响应式的数据

2.2.语法:const xxx = ref(initValue)

        创建一个包含响应式数据的引用对象(reference对象)

        JS中操作数据:xxx.value

        模板中读取数据:不需要.value,直接<div>{{xxx}}<div>

备注:

        接收的数据可以是:基本类型、也可以是对象类型

        基本类型的数据:响应式依然是靠Object.defineProperty()的get与set完成的

        对象类型的数据:内部“求助”了Vue3.0中的一个新函数------reactive函数

        (ref处理基本类型用的是get与set处理对象数据用的是es6中的Proxy)

<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{name}}</h2>
  <h2>年龄:{{age}}</h2>
  <h3>工作岗位:{{job.type}}</h3>
  <h3>薪水:{{job.salary}}</h3>
  <button @click="changeInfo">修改人的信息</button>
</template>

<script>
import {ref} from 'vue'
export default {
  name: 'App',
  setup(){
    //数据
    let name = ref('李四')
    let age = ref(20)
    let job = ref({
      type:'前端工程师',
      salary:'30k'
    })

    //方法
    function changeInfo(){
      name.value = '张三'
      age.value = 19
      job.value.type = 'UI设计师'
      job.value.salary = '55k'
    }

    //返回一个对象
    return{
      name,
      age,
     changeInfo,
     job
    }
  }
}
</script>

<style>
</style>

3.reactive函数

3.1.作用:定义一个对象类型的响应式数据(基本类型别用它,用ref函数)

3.2语法:const代理对象=reactive(被代理对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称Proxy对象)

3.3reactive定义的响应式数据是“深层次的”。

3.4内部基于es6的Proxy实现,通过代理对象操作源对象内部数据都是响应式的

<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h3>工作岗位:{{person.job.type}}</h3>
  <h3>薪水:{{person.job.salary}}</h3>
  <h3>爱好:{{person.hobby}}</h3>
  <h3>测试c:{{person.job.a.b.c}}</h3>
  <button @click="changeInfo">修改人的信息</button>
</template>

<script>
import {reactive} from 'vue'
export default {
  name: 'App',
  setup(){
    //数据
    let person = reactive({
      name:'李四',
      age:20,
      job:{
        type:'前端工程师',
        salary:'30k',
        a:{
          b:{
            c:999
          }
        }
      },
      hobby:['吃饭','学习','睡觉']

    })
    
    //方法
    function changeInfo(){
      person.name = '张三'
      person.age = 19
      person.job.type = 'UI设计师'
      person.job.salary = '55k'
      person.job.a.b.c = '0000'
      person.hobby[0] = '打游戏'
    }

    //返回一个对象
    return{
      person,
     changeInfo,
    }
  }
}
</script>

<style>
</style>

4.Vue3.0中的响应式原理

vue2.x的响应式

实现原理:

        对象类型:通过Object.defineProperty()对对象的已有属性值得读取、修改进行拦截(数据劫持)

        数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)

Object.defineProperty(data,'count',{
  get(){},
  set(){}
})

存在问题:

        新增属性、删除属性,界面不会更新

        直接通过下标修改数组,界面不会自动更新

Vue3.0的响应式

实现原理:

        通过Proxy(代理):拦截对象中任意属性的变化,包括:属性值得读写、属性的添加、属性的删除等。

        通过Reflect(反射):被代理对象(源对象)的属性惊醒操作

const p = new Proxy(person, {
                //查 有人读取p的某个属性时调用
                get(target, propName) {
                    console.log(`有人读取了p身上的${propName}属性`);
                    return Reflect.get(target, propName);
                },
                //增,改 有人给p增加某个属性时调用或修改p的某个属性
                set(target, propName, value) {
                    console.log(
                        `有人读取了p身上的${propName}属性,我要去修改页面了`
                    );
                    Reflect.set(target, propName, value);
                },
                //删 有人删除p的某个属性时调用
                deleteProperty(target, propName) {
                    console.log(
                        `有人删除了p身上的${propName}属性,我要去修改页面了`
                    );
                    return Reflect.deleteProperty(target, propName);
                },
            });

 5.reactive对比ref

从定义数据角度对比:

        ref用来定义:基本类型数据。

        reactive用来定义:对象(或数组)类型数据

        备注:ref也可以用来定义对象(或数组)类型数据,它内部会自动通过reactive转为代理对象

从原理角度对比:

        ref通过Object.defineProperty()的get()与set()来实现响应式(数据劫持)

         reactive通过使用Proxy来实现响应式(数据劫持),并通过Reflect操作源对象内部的数据

从使用角度对比:

        ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value

        reactive定义的数据:操作数与读取数据:均不需要.value

6.setup的两个注意点

setup执行的时机

        在beforeCreate之前执行一次,this是undefined。

setup的参数

        props:值为对象,包含:组件外部传递过来,但没有在props配置中生明的属性,相当于this.$atters。

        slots:收到的插槽内容,相当于this.$slots。

        emit:分发自定义事件的函数,相当于this.$emit。

App:

<template>
  <Demo @hello="showHelloMsg" mag="你好啊" name="chubagui">
    <template v-slot:qwe>
      <span>学习</span>
    </template>
  </Demo>
</template>

<script>
import Demo from'./components/Demo.vue'
export default {
  name:'App',
  components:{
    Demo
  },
  setup(){
    function showHelloMsg(value){
      alert(`你好啊,你触发了hello事件,我收到的参数是:${value}`)
    }
    return{
      showHelloMsg
    }
  }

}
</script>

组件:

<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <button @click="test">测试触发一下Demo组件的Hello事件</button>
</template>

<script>
import {reactive} from 'vue'
export default {
  name: 'Demo',
  props:['msg','name'],
  emits:['hello'],
  setup(props,context){
    //   console.log('---setup---',props)
    // console.log('----setup---',context.attrs)//相当于vue2中的$attrs
    // console.log('----setup---',context.emit)//触发自定义事件
    console.log('----setup---',context.slots)//插槽
    
    //数据
    let person = reactive({
      name:'李四',
      age:20,
    })
    //方法
    function test(){
        context.emit('hello',666)
    }
    
    //返回一个对象
    return{
      person,
      test
    }
  }
}
</script>

<style>
</style>

7.计算属性与监视

1.computed函数

与Vue2.x中的computed配置功能一致

写法:

<template>
  <h1>一个人的信息</h1>
  姓:<input type="text" v-model="person.firstName"> 
  <br>
  名:<input type="text" v-model="person.lastName"> 
  <!-- 只读 -->
  <br>
  <!-- <span>全名:{{person.fullName}}</span> -->
  全名:<input type="text" v-model="person.fullName">
</template>

<script>
import {reactive,computed} from 'vue'
export default {
  name: 'Demo',
  
  setup(){
    //数据
    let person = reactive({
      firstName:'李',
      lastName:'四'
      
    })

    //计算属性---简写(不考虑计算属性被修改的情况)
    // person.fullName = computed(()=>{
    //     return person.firstName + '-' +person.lastName
    // })
    //计算属性---完整版(考虑读和写)
    person.fullName = computed({
        get(){
            return person.firstName + '-' +person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
    
    //返回一个对象
    return{
      person,
    }
  }
}
</script>


2.wetch函数:

与vue2.x中watch配置功能一致

注意:

        监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)

        监视reactive定义的响应式数据中的某个属性(属性为对象时)时:deep配置有效

组件:

<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>信息为:{{msg}}</h2>
  <button @click="msg+='!'">修改信息</button>
  <hr>
  <h2>一个人的信息:</h2>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h3>工资:{{person.job.j1.salary}}</h3>
  <button @click="person.name += '~'">修改姓名</button>
  <button @click="person.age++">修改年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>
</template>

<script>
import {ref,reactive,watch} from 'vue'
export default {
  name: 'Demo',
  setup() {
    //数据
    let sum = ref(0)
    let msg = ref("nihao")
    let person = reactive({
      name:'李四',
      age:39,
      job:{
        j1:{
          salary:20
        }
      }
    })

    //情况一:监视ref所定义的一个响应式数据
    // watch(sum,(newValue,oldValue)=>{
    //   console.log('sum变了',newValue,oldValue)
    // },{immediate:true})

    //情况二:监视ref所定义的多个响应式数据
    // watch([sum,msg],(newValue,oldValue)=>{
    //   console.log('sum或msg变了',newValue,oldValue)
    // },{immediate:true})

    //情况三:监视reactive所定义的一个响应式数据的全部属性
    //1.此处无法正确的获取oldValue
    //2.强制开启了深度监视,且无法关闭(deep配置无效)
    // watch(person,(newValue,oldValue)=>{
    //   console.log('person变了',newValue,oldValue)
    // },{immediate:true,deep:false})

    //情况四:监视reactive所定义的一个响应式数据的某个属性
    //  watch(()=>person.age,(newValue,oldValue)=>{
    //    console.log('年龄变了',newValue,oldValue)
    //  },{immediate:true})

    //情况四:监视reactive所定义的一个响应式数据的某些属性
    // watch([()=>person.age,()=>person.name],(newValue,oldValue)=>{
    //    console.log('年龄或姓名变了',newValue,oldValue)
    //  })

     //特殊情况
     //此处由于监视的是reactive定义的对象中的某个属性,所以deep有效
      watch(()=>person.age,(newValue,oldValue)=>{
        console.log('年龄变了',newValue,oldValue)
      },{deep:true})

    //返回一个对象
    return{
      sum,
      msg,
      person
    }
  }
}
</script>

<style>

</style>

注意:

watch中监视的是ref定义的数据不用.value,reactive定义的数据要用.value

<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>信息为:{{msg}}</h2>
  <button @click="msg+='!'">修改信息</button>
  <hr>
  <h2>一个人的信息:</h2>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h3>工资:{{person.job.j1.salary}}</h3>
  <button @click="person.name += '~'">修改姓名</button>
  <button @click="person.age++">修改年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>
</template>

<script>
import {ref,reactive,watch} from 'vue'
export default {
  name: 'Demo',
  setup() {
    //数据
    let sum = ref(0)
    let msg = ref("nihao")
    let person = ref({
      name:'李四',
      age:39,
      job:{
        j1:{
          salary:20
        }
      }
    })
    watch(sum,(newValue,oldValue)=>{
      console.log('sum变了',newValue,oldValue)
    })
    //方式一
    watch(person.value,(newValue,oldValue)=>{
      console.log('person变了',newValue,oldValue)
    })
    //方式二
    watch(person,(newValue,oldValue)=>{
      console.log('person变了',newValue,oldValue)
    },{deep:true})

    //返回一个对象
    return{
      sum,
      msg,
      person
    }
  }
}
</script>

<style>

</style>

3.watchEffect函数

watch的套路是:既要指明监视的属性,也要指明监视的回调。

watchEffect的套路是:不用指明监视那个属性,监视的回调中用到那个属性,那就监视那个属性。

watchEffect有点像computed:

        但computed注重的是计算出来的值(回调函数的返回值),所以必须要写返回值。

        而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。

//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调
    watchEffect(()=>{
      const x1 = sum.value
      const x2 = person.age
      console.log('watchEffect配置的回调执行了')
    })

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值