vue3.0各种基本composition api

本文深入探讨Vue3.0引入的Composition API,包括setup函数、ref、reactive、toRef、toRefs、watch、生命周期钩子的使用等核心概念,揭示其如何提升组件复用性和代码组织性。

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

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>{{ myObj.name }}</h2>
    <div></div>
    <van-button @click.stop="onAddCount" square type="primary">单次累加:({{ count }})</van-button>
    <div style="margin-top: 20px;"></div>
    <van-button @click.stop="onAddDoubleCount" square type="primary">双次累加:({{ doubleCount }})</van-button>
  </div>
</template>

<script>
import { otherApi } from '@/api/userApi'
import {
  ref, // 原始类型(基本类型)
  reactive, // 对象类型
  toRefs, // 保证 reactive 对象属性保持响应性
  computed, // 计算属性
  watch, // 监听数据
  watchEffect, // 监听响应式数据
  onMounted,
  onRenderTracked,
  onRenderTriggered,
  getCurrentInstance,
} from 'vue'

export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  setup(props) {
    const { ctx } = getCurrentInstance()
    onMounted(() => {})
    // onRenderTracked((e) => {
    //   console.log(e)
    // })
    // onRenderTriggered((e) => {
    //   console.log(e)
    // })

    let count = ref(0)
    let doubleCount = ref(0)
    const myObj = reactive({
      name: 'xs',
    })

    // 监听单个数值
    watch(count, (val, prevVal) => {
      //console.log(count.value, val)
    })

    // 监听双数值
    watch(doubleCount, (val, prevVal) => {
      //console.log(`当前doubleCount:${val},先前doubleCount:${prevVal}`)
    })

    // 监听对象
    watch(
      () => {
        return myObj.name
      },
      (val, prevVal) => {
        console.log(`监听myObj对象:${val}, ${prevVal}`)
      }
    )

    watchEffect(() => {
      //console.log(`watchEffect:${myObj.name}`)
    })

    // 改变单数值
    const onAddCount = () => {
      myObj.name = 'uy'
      count.value++
    }

    // 改变双数值
    const onAddDoubleCount = () => {
      doubleCount.value += 2
    }

    // 获取数据
    const loadData = async () => {
      try {
        let res = await otherApi.fetchAreaAll()
        console.log(res)
      } catch (error) {}
    }

    //loadData()

    return {
      count,
      myObj,
      doubleCount,
      onAddCount,
      onAddDoubleCount,
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值