example of creating a vue component
Creating a Vue component typically involves defining its template, script (logic), and optional styles within a Single-File Component (SFC) using the
.vue extension.Here is an example of a simple button counter component:
ButtonCounter.vue<template>
<button @click="count++">You clicked me {{ count }} times.</button>
</template>
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
<style scoped>
button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 8px;
}
</style>
Explanation:
-
This section defines the component's HTML structure. In this case, it's a
<button>element.@click="count++": This is a Vue directive that listens for theclickevent on the button and increments thecountdata property when triggered.{{ count }}: This uses text interpolation to display the current value of thecountdata property.
-
This section contains the component's JavaScript logic.
export default {}: This exports a JavaScript object that defines the component's options.data(): This function returns an object containing the component's reactive data properties. Here,countis initialized to0.
-
This section defines the component's CSS styles.
scoped: This attribute ensures that the styles defined within this<style>block are only applied to this specific component and do not globally affect other parts of your application.
Using the component in
App.vue (or another parent component):<template>
<div id="app">
<h1>My Vue App</h1>
<ButtonCounter />
<ButtonCounter /> <!-- You can reuse components -->
</div>
</template>
<script>
import ButtonCounter from './components/ButtonCounter.vue';
export default {
components: {
ButtonCounter
}
}
</script>
Explanation:
import ButtonCounter from './components/ButtonCounter.vue';: This line imports theButtonCountercomponent.components: { ButtonCounter }: This registers theButtonCountercomponent, making it available for use within theAppcomponent's template.<ButtonCounter />: This is how you use the imported component within your template, treating it like a custom HTML tag. Each instance of<ButtonCounter />will have its own independentcountdata