Skip to main content

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
Code
<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:
  • <template>
    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 the click event on the button and increments the count data property when triggered.
    • {{ count }}: This uses text interpolation to display the current value of the count data property.
  • <script>
    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, count is initialized to 0.
  • <style scoped>
    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):
Code
<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 the ButtonCounter component.
  • components: { ButtonCounter }This registers the ButtonCounter component, making it available for use within the App component'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 independent count data