当前位置: 首页 > news >正文

插槽、生命周期

##### 购物车加减操作关键代码

```vue

<template>

        <tr v-for="(item,index) in products">

            <input type="button" value="-" @click="btnA(index)">

            <input type="text" v-model="item.quantity">

            <input type="button" value="+" @click="btnB(index)">

            <input type="button" value="移除" @click="btnRemove(index)">

        </tr>

</template>

<script>

    let totlaAmount = computed(()=>{

      let tmp = products.value.reduce((a,b)=>{

        return a += b.price * b.quantity

      },0)

      return tmp

    })

    const btnA = (index) =>{

      products.value[index].quantity --

    }

    const btnB = (index) =>{

      products.value[index].quantity ++

    }

    const btnRemove = (index) =>{

     products.value.splice(index,1)

    }

</script>

```



 

### 笔记

### 插槽(Slots)

1. 概念:在组件中使用 `<slot>` 元素作为占位符,可将父组件传递进来的内容渲染到指定位置。

```vue

<template>

    <ButtonCounter>

      8888

        <Profile></Profile>

    </ButtonCounter>

</template>

<script setup>

import ButtonCounter from './components/ButtonCounter.vue'

import Profile from './components/Profile.vue';

import {ref, shallowRef} from 'vue'

// let cc = ref(ButtonCounter)

let cc = shallowRef(ButtonCounter)

let count = 1

function btn(){

  count ++

  if(count % 2 === 0){

    cc.value = Profile

  }else{

    cc.value = ButtonCounter

  }

}

</script>

```

2. [动态组件]实现方式:通过 Vue 的 `<component>` 元素和特殊的 `is` attribute 来实现组件的动态切换

```vue

<template>

  <component :is="cc"></component>

  <input type="button" value="点下" @click="btn">

</template>

```

### 生命周期钩子

- 概念:每个 Vue 组件实例在创建时会经历一系列初始化步骤,在此过程中会运行生命周期钩子函数,让开发者有机会在特定阶段运行自己的代码

- 常用钩子:onMounted、onUpdated、onUnmounted

- 注册方式:在组件初始化时同步注册生命周期钩子。例如,在 `<script setup>` 中调用 `onMounted()` 等钩子函数

- 注意事项:不要在异步函数中注册生命周期钩子,否则可能导致当前组件实例丢失,钩子无法正常工作




 

相关文章:

  • RabbitMQ消息的重复消费问题如何解决?
  • 港大今年开源了哪些SLAM算法?
  • Cluster Interconnect in Oracle RAC
  • 一些模型测试中的BUG和可能解决方法
  • PostgreSQL逻辑复制(logic replication)
  • [AI ][Dify] Dify Tool 插件调试流程详解
  • 浅聊大模型-有条件的文本生成
  • 具身智能时代的机器人导航和操作仿真器综述
  • MySQL数据库故障排查与解决方案
  • 窗口函数row_number() OVER()对每个组内的行按照特定条件进行编号
  • 免布线视频桩:智慧城市停车降本增效的破局利器
  • 《循序渐进linux》
  • AWS IoT Core与MSK集成实战:打造高可靠实时IoT数据管道
  • 【C++设计模式之Strategy策略模式】
  • 学习心得《How Global AI Policy and Regulations Will Impact Your Enterprise》Gartner
  • 文本框碰撞测试
  • C++AVL树
  • 访问网页的全过程(分步骤的详细解析)
  • 通过Linux系统服务管理IoTDB集群的高效方法
  • C++ -- string
  • 韩国前国务总理韩德洙加入国民力量党
  • 赵作海因病离世,妻子李素兰希望过平静生活
  • 阿里CEO:将以饱和式投入打法,聚焦几大核心战役
  • 75岁亚当·费舍尔坐镇,再现80分钟马勒《第九交响曲》
  • 昆明阳宗海风景名胜区19口井违规抽取地热水,整改后用自来水代替温泉
  • 泉州一家婚介机构广告牌越南新娘七天闪婚领证?市监部门介入