vue3+Ts 2 组件+生命周期

计算属性 computed

<template>
  <div>{
  { arr }}</div>
  <button @click="arr.push('新学生')">添加学生(当前已有{
  { studentNumber }}个学生)</button>
</template>

<script setup>
import { ref, computed } from 'vue'

const arr = ref(['tom', 'rose'])

// // 计算属性步骤一,编写计算的函数
// const getLength = () => {
//   return arr.value.length
// }
// // 计算属性步骤二, 用 computed 包住这个函数, 处理过后就会返回一个计算属性
// const studentNumber = computed(getLength)

// 另外一种写法,就是直接拼在一起, 写回调函数即可
const studentNumber = computed(() => {
  return arr.value.length
})

</script>

监听器watch

// 监听器基本使用
watch(iphone, () => {
  localStorage.setItem('cart', JSON.stringify(iphone))
})

// 监听器使用细节
// 监听一个数据
watch(num1, (newVal, oldVal) => {
  co

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3 中,你可以通过 `ref` 和 `setup` 函数来获取子组件实例,并且调用其方法。 假设你有一个父组件 `Parent` 和一个子组件 `Child`,需要在父组件中调用 `Child` 组件的方法,可以按照以下步骤进行: 1. 在子组件中,使用 `ref` 创建一个引用: ```vue <template> <div>子组件</div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ setup() { const childRef = ref(null); const childMethod = () => { console.log('子组件方法被调用了'); }; return { childRef, childMethod, }; }, }); </script> ``` 在 `setup` 函数中,我们创建了一个名为 `childRef` 的引用,并将其初始化为 `null`。在 `childMethod` 中,我们定义了一个子组件的方法,用于在父组件中调用。 2. 在父组件中,使用 `ref` 创建一个引用,并在 `onMounted` 生命周期钩子函数中通过 `childRef.value` 获取子组件实例: ```vue <template> <div> <button @click="callChildMethod">调用子组件方法</button> <Child ref="childRef"></Child> </div> </template> <script lang="ts"> import { defineComponent, onMounted, ref } from 'vue'; import Child from './Child.vue'; export default defineComponent({ components: { Child, }, setup() { const childRef = ref(null); const callChildMethod = () => { if (childRef.value) { childRef.value.childMethod(); } }; onMounted(() => { childRef.value = childRef.value.$refs.child; }); return { childRef, callChildMethod, }; }, }); </script> ``` 在 `setup` 函数中,我们创建了一个名为 `childRef` 的引用,并将其初始化为 `null`。在 `callChildMethod` 中,我们通过 `childRef.value` 获取子组件实例,并调用其 `childMethod` 方法。在 `onMounted` 生命周期钩子函数中,我们通过 `childRef.value.$refs.child` 获取子组件实例,并将其存储在 `childRef.value` 中。 注意,我们在父组件模板中使用了 `Child` 组件,并将其通过 `ref` 绑定到了 `childRef` 引用上。在 `onMounted` 生命周期钩子函数中,我们可以通过 `childRef.value.$refs.child` 获取到子组件实例。这里的 `child` 是子组件模板中的 `ref` 名称,用于获取子组件实例。 这样,就可以在父组件中调用子组件的方法了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值