插槽、生命周期

购物车加减操作关键代码

```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.valueindex.quantity --

}

const btnB = (index) =>{

products.valueindex.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>

```

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

```vue

<template>

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

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

</template>

```

生命周期钩子

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

  • 常用钩子:onMounted、onUpdated、onUnmounted

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

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

相关推荐
东方小月18 分钟前
从零开发一个 Coding Agent(十二):实现版本化 JSONL 与真实 CLI 入口
前端·设计模式·前端框架
FL16238631291 小时前
室内易燃物识别易燃评估室内易燃程度识别分割数据集labelme格式1015张85类别
java·服务器·前端
用户059540174461 小时前
把 AI 长期记忆去重测试从 20 分钟压到 40 秒,重复率从 18% 干到 1.5%
前端·css
kyriewen2 小时前
我把 AI 写的并发请求控制器手写了一遍——3 个语义我当时根本讲不清
前端·javascript·面试
_codemonster2 小时前
Vue中的ref和reactive到底在干嘛
前端·javascript·vue.js
IT_陈寒3 小时前
为什么我的JavaScript闭包总是漏掉那个变量?
前端·人工智能·后端
两只羊ovo3 小时前
前端八股之 storage & this:两个最容易卡住的点,一次讲透
前端
用户921080262863 小时前
Bubble 打字机效果实践:从项目配置到源码实现
前端
张元清3 小时前
React useEventListener Hook:类型安全的 DOM 事件监听 (2026)
javascript·react.js