Vue3新特性

本文详细介绍了Vue3中ref和reactive的区别与用法,以及它们在响应式系统中的作用。通过示例展示了如何在模板中使用ref来更新值,并解释了reactive对于复杂类型的处理。同时,文章涵盖了Vue3的生命周期变化,包括beforeCreate、created等钩子函数的新对应关系,并提供了onMounted和onUpdated等新生命周期钩子的使用示例。此外,还讨论了watch功能和Teleport组件的使用,Teleport允许将内容渲染到指定的DOM位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ref语法

ref是一个函数,接受一个参数(一般传入原始类型),返回一个响应式对象

<template>
  <div id="nav">
    <p>{{count}}</p>
    <button @click="increase">click</button>
  </div>
  <router-view />
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
export default defineComponent({
  setup () {
    const count = ref(0)
    const increase = () => {
      count.value++
    }
    return {
      count,
      increase
    }
  }
})
</script>
<style>
</style>

Reactive函数

Reactive函数可以接受复杂类型,可直接传入一个对象。但是如果将返回的值,进行解构再使用,会使其失去响应式。可通过toRefs()函数解决

<template>
  <div id="nav">
    <p>{{count}}</p>
    <p>{{double}}</p>
    <button @click="increase">click</button>
  </div>
  <router-view />
</template>

<script lang="ts">
import { computed, defineComponent, reactive, toRefs } from 'vue'
interface DataProps {
  count: number;
  double: number;
  increase: () => void;
}
export default defineComponent({
  setup () {
    const data: DataProps = reactive({
      count: 0,
      increase: () => {
        data.count++
      },
      double: computed(() => data.count * 2)
    })
    const refData = toRefs(data)
    return {
      ...refData
    }
  }
})
</script>
<style>
</style>

vue3生命周期

beforeCreate --> use setup()
created --> use setup()
beforeMount --> onBeforeMount()
mounted --> onMounted()
beforeUpdate --> onBeforeUpdate()
updated --> onUpdated()
beforeDestory --> onBeforeUnMount()
destoryed --> onUnMounted()
activated --> onActivated()
deacticated --> onDeactivated()
errorCaptured --> onErrorCaptured


// added  用于调试 观测数据变化
onRenderTracked
onRenderTriggered

// 一般都是以一个回调函数作为参数
eg: 
onMounted(() => {
      console.log('onmounted')
})
onUpdated(() => {
  console.log('onUpdated')
})
onRenderTriggered((event) => {
  console.log(event)
})

watch

// 监听一个值
watch(greeting, (newValue, oldValue) => {
      console.log('new==>', newValue)
      console.log('old==>', oldValue)
})
// 监听一个数组
watch([greeting, data], (newValue, oldValue) => {
  console.log('new==>', newValue)
  console.log('old==>', oldValue)
})
// 监听某个对象中的某个属性
watch([greeting, () => data.count], (newValue, oldValue) => {
  console.log('new==>', newValue)
  console.log('old==>', oldValue)
})

defineComponent

对ts比较友好的一个方法,用于包裹属性

Teleport

// 可直接将组件传送到某个DOM元素上
// teleport标签上有个to属性,里面接收一个css query selector 作为参数
<teleport to="#modal">
  <div id="center">
    <h1>this is a modal</h1>
  </div>
</teleport>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值