Vue3,组合式API


vue3优势

更易维护

更快的速度

更小的体积

更优的数据响应式

create-vue是vue官方新的脚手架工具,底层切换到vite(下一代构建工具)

APP.vue中结构(<script><template><style>)变化,便于编写代码

组合式API-setup

setup允许在script中编写组合式API,不再要求唯一根元素

执行时机:在beforeCreate钩子之前

在setup函数中写的数据和方法,需要在末尾以对象方式return,才能给模板使用

<script>
  export default {
    setup(){
      const message = 'this is message'
      const logMessage = ()=>{
        console.log(message)
      }
      // 必须return才可以
      return {
        message,
        logMessage
      }
    }
  }
</script>

所以出现<script setup>语法糖

<script setup>
  export default {
      const message = 'this is message'
      const logMessage = ()=>{
        console.log(message)
      }
      // 不需要return
  }
</script>

组合式API-reactive和ref函数

1、reactive

接受对象类型数据的参数传入并返回一个响应式对象

<script setup>
 // 导入
 import { reactive } from 'vue'
 // 执行函数 传入参数 变量接收
 const state = reactive({
   msg:'msg'
 })
 const setSate = ()=>{
   // 修改数据更新视图
   state.msg = 'this is new msg'
 }
</script>

<template>
  {{ state.msg }}
  <button @click="setState">change msg</button>
</template>

2、ref

接受简单类型或者对象类型的数据传入并返回一个响应式对象

<script setup>
 // 导入
 import { ref } from 'vue'
 // 执行函数 传入参数 变量接收
 const count = ref(0)
 const setCount = ()=>{
   // 修改数据更新视图必须加上.value
   count.value++
 }
</script>

<template>
  <button @click="setCount">{{count}}</button>
</template>

本质:在原有传入数据基础上,外包一层对象,包成复杂数据类型,再借助reactive实现响应式

脚本区调用加.value,非脚本区不加

reactive和ref异同

  1. 都是用来生成响应式数据

  2. 不同点

    1. reactive不能处理简单类型的数据

    2. ref参数类型支持更好,但是必须通过.value做访问修改

    3. ref函数内部的实现依赖于reactive函数

组合式API-computed

与vue2保持一致

<script setup>
// 导入
import {ref, computed } from 'vue'
// 原始数据
const count = ref(0)
// 计算属性
const doubleCount = computed(()=>count.value * 2)

// 原始数据
const list = ref([1,2,3,4,5,6,7,8])
// 计算属性list
const filterList = computed(item=>item > 2)
</script>

组合式API-watch

监听单个数据(监听多个数据将第一个参数写成数组)

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  // 2. 调用watch 侦听变化
  watch(count, (newValue, oldValue)=>{
    console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
  })
</script>

watch对ref对象默认浅层侦听,直接修改嵌套对象属性不会触发回调执行

要开启深度监听

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const state = ref({ count: 0 })
  // 2. 监听对象state
  watch(state, ()=>{
    console.log('数据变化了')
  })
  const changeStateByCount = ()=>{
    // 直接修改不会引发回调执行
    state.value.count++
  }
</script>

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const state = ref({ count: 0 })
  // 2. 监听对象state 并开启deep
  watch(state, ()=>{
    console.log('数据变化了')
  },{deep:true})
  const changeStateByCount = ()=>{
    // 此时修改可以触发回调
    state.value.count++
  }
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值