函数式组件

本文介绍了如何使用Vue的函数式组件创建一个列表,组件接收props并响应点击事件改变颜色。它展示了函数式组件的特点,如无状态和不触发生命周期钩子。

函数式组件是一种定义自身没有任何状态的组件的方式。它们就像纯函数:接受props,返回vnodes。函数式组件在渲染过程中不会创建组件实例(也就是说,没有this),也不会触发常规的组件生命周期钩子。

下面用一个例子来学习函数式组件:

<script setup lang='ts'>

import { ref ,h} from "vue"

/**
 * Implement a functional component :
 * 1. Render the list elements (ul/li) with the list data
 * 2. Change the list item text color to red when clicked.
*/

const ListComponent = (props, { emit }) => { 
  const children = []
    props.list.map((item,index)=>{
    children.push(
      h('li', {
        style: {
        color: index ===  props['active-index'] ? 'red' : '#333'
        },
        onClick:()=>{
          emit('toggle',index)
        }},item.name)
      )
    })
  return h('ul',children)
}  


const list = [{
  name: "John",
}, {
  name: "Doe",
}, {
  name: "Smith",
}]  

const activeIndex = ref(0)

function toggle(index: number) {
  activeIndex.value = index
}

</script>

<template>
  <list-component
    :list="list"
    :active-index="activeIndex"
    @toggle="toggle"
  />
</template>

该例子实现的效果是点击文字时,文字会变为红色

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值