当前位置: 首页 > 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()` 等钩子函数

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




 

http://www.dtcms.com/a/180957.html

相关文章:

  • 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
  • C++:求分数序列和
  • 强化学习PPO算法学习记录
  • 【Pandas】pandas DataFrame clip
  • GET请求如何传复杂数组参数
  • 使用oracle goldengate同步postgresql到postgresql
  • Eclipse SWT 1 等比缩放
  • Web端项目系统访问页面很慢,后台数据返回很快,网络也没问题,是什么导致的呢?
  • 文件包含2
  • OpenCV的 ccalib 模块用于自定义标定板的检测和处理类cv::ccalib::CustomPattern()----函数calibrate
  • 火山引擎火山云主推产品