X

XiaoSong

V1

2023/02/12阅读:26主题:默认主题

vue3组件基础

为什么使用组件

在我们平时开发中常常会出现几个结构相似的页面,为了避免代码重复,我们可以把其封装成一个组件。这是不是和我们写一个可复用的工具函数的思想比较类似。使用组件也可以使我在做页面的时候像搭积木一样,一个页面由若干个组件堆成。

定义一个组件

我们会把组件写在后缀名为.vue的文件中,被叫做单文件组件也就是所谓的SFC(Single file component)。下面我们写一个简单的button组件。文件名Button.vue

<template>
    <div class="btn" @click="add">
        {{ num }}
    </div>
</template>

<script setup>
import {ref} from 'vue'
  
const num = ref(0)
const add = () => { 
    num.value ++
}
</script>

<style scoped>
.btn { 
    background-color#42b883;
    padding10px;
    color: white;
    text-align: center;
    font-weight: bold;
    border-radius10px;
    margin-bottom10px;
}
</style>

使用组件

要在父组件中使用一个组件,我们只需要引入组件文件即可:

<!-- 使用Button组件 -->
<template>
    <div>
        <Button/>
    </div>
</template>

<script setup>
import Button from '../components/childComponent/Button.vue'
</script>

组件使用成功了

组件可以使用多次,每一次使用就是创建了一个实例,里面的状态都是独立的,所以以下这三个按钮可以点击出各自不同的数字

<Button/>
<Button/>
<Button/>
<Button/>

NOTES: 1. 这里与Vue2不同的是,引入组件文件后可以直接使用不需要注册了。

分类:

前端

标签:

Vue.js

作者介绍

X
XiaoSong
V1