www.thisdot.co
Open in
urlscan Pro
2600:9000:2156:f000:5:84f5:bec0:93a1
Public Scan
URL:
https://www.thisdot.co/blog/building-reusable-components-in-vue-3/
Submission: On June 21 via api from US — Scanned from DE
Submission: On June 21 via api from US — Scanned from DE
Form analysis
0 forms found in the DOMText Content
Skip to content * services * trainings * portfolio * about * blog * resources * all resources * framework.dev * events & podcasts * javaScript marathon * analyze * Contact Us * VueJS BUILDING REUSABLE COMPONENTS IN VUE 3 Mark Shenouda Jun 8 4 min read vue 3VueJSvue đWHAT IS VUE Vue.js is an open-source modelâviewâviewmodel front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You. From its official documentation âVue is a JavaScript framework for building user interfaces. It builds on top of standard HTML, CSS and JavaScript, and provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be it simple or complex.â đCOMPONENTS BASICS The way we build apps and websites in Vue is different than using pure HTML, CSS, and JavaScript. In Vue, the app is like a tree of components. đTWO WAYS TO WRITE VUE COMPONENTS There are two ways to write Vue components: the old (classic) way, by using Vue class component, and the new (modern) way by using script setup and composition APIs. đFILE STRUCTURE IN BOTH WAYS Vue follows the same file structure in both ways. First, each component should be in a separate file with the .vue extension, and each Vue file contains three sections. <template> We write the HTML template here. </template> <script> // We write the JavaScript logic here. </script> <style> /* We write the CSS styles for the component here. */ </style> Both ways share the same file structure. The only difference is in the <script> section. đIN THE VUE CLASS COMPONENTS WAY The <script> section should return the Vue object like this: <script> export default { name: âcomponent-nameâ, props: { // ⊠}, data() { // ⊠}, // ⊠} </script> Then we use script setup: <script setup> // We put our componentâs JavaScript code here: </script> The new way is more minimal, and we access all the Vue component class features using composition APIs (itâs more like React hooks for React if youâre familiar with React). đCOMPONENT REGISTRATION Each component you create in your Vue app should be registered so Vue knows where to locate its implementation when it is encountered in a template. To register your component in another component, you should add it to the components property in the Vue object. <template> <AnotherComponent /> </template> <script> import AnotherComponent from './AnotherComponent.vue' export default { components: { AnotherComponent } } </script> In the script setup way, you donât need to manually register components. They are being registered automatically when you import them: <script setup> import AnotherComponent from â./AnotherComponent.vueâ; </script> <template> <AnotherComponent /> </template> đPROPS Props allow developers to pass data from the parent component to children components. Vue components require explicit props declarations so that Vue knows what external props passed to the component should be treated as fall through attributes. <AnotherComponent message=âHello world!â /> To declare props in your component, you should add them in the props property in the Vue object: <script> export default { props: { title: String, likes: Number } } </script> For each property in the object declaration syntax, the key is the name of the prop, while the value should be the constructor function of the expected type. Note: itâs important to declare each Propâs type too to avoid errors in production. In script setup, you define props with defineProps() from composition APIs: <script setup> const props = defineProps({ title: String, likes: Number }) </script> đNOW LETâS BUILD A TODO APP The best way to practice these concepts is by building a small app. First, letâs initialize a new project using Vite: npm init vite@latest Or you can use Stackblitz like me in this tutorial. Go to the Vite tab and choose Vue: Go to App.js, remove its content, and add the title. Let's create the List component where we will show the user all of the todos. <script setup> defineProps({ todos: Array, }); </script> <template> <ul> <li v-for="todo in todos"> {{ todo }} </li> </ul> </template> As you see, it's a very simple component. We just pass the todos array as a prop, and then use v-for to print it. Then, import the list component so we can use it in App.js. <script setup> import List from './components/List.vue'; </script> <template> <h1>Todo List</h1> <List /> </template> Now, let's create the form to add todos from. <template> <h1>Todo List</h1> <List /> <form> <input type="text" placeholder="Write a new task" /> <button type="submit">Add</button> </form> </template> We will now need to add the states. In the new approch, we use ref(). <script setup> import { ref } from 'vue'; const todos = ref([]); const newTodo = ref(""); </script * todos is where we will store all the todos * newTodo is to store the current form value Then, we need to bind these states with the <List /> component, and the form input. <List :todos="todos" /> <input type="text" placeholder="Write a new task" v-model="newTodo" /> Finally, we need to create the submit function to add a new todo on submit, and clear the form for a new one. function handleSubmit() { todos.value.push(newTodo); newTodo.value = ''; } Then, bind this function with the form. <form @submit.prevent="handleSubmit"> Here is the complete project for you to check out and try yourself! If you need additional assistance, feel free to reach out to me on Twitter! -------------------------------------------------------------------------------- This Dot Media is focused on creating an inclusive and educational web for all. We keep you up to date with advancements in the modern web through events, podcasts, and free content. To learn, visit thisdot.co. Hire us -------------------------------------------------------------------------------- MARK SHENOUDA @MarkSShenouda@markshenouda YOU MIGHT ALSO LIKE VueJS MAKING SENSE OF MULTIPLE V-MODEL BINDINGS IN VUE 3 VueJS TAKE YOUR APP TO THE NEXT LEVEL WITH VUE 3 VueJS INTRODUCING THE RELEASE OF VUE 3 VueJS HOW TO SET UP STORYBOOK IN VUEJS LET'S WORK TOGETHER Do you want to have the job done? We are ready to provide our expertise! Contact us WE'RE HIRING Software ArchitectTechnical Project ManagerShow all jobs This Dot Labs proudly partners with enterprises interested in transforming their digital assets, upskilling their teams, and finding novel avenues for advanced integration. Sign up for our newsletters * services * trainings * portfolio * certifications * apprentice program * press releases * about * blog * team * jobs * contact * * * * * * Code of Conduct * Privacy Policy * Cookie Policy * Terms of Use * +1-669-293-7368 © 2022 This Dot, Inc. Live chat CHAT WITH THIS DOT Hi! How can we help you? Close Chat Prompt We use cookies to improve user experience and analyze website traffic. By clicking âAcceptâ, you agree to our website's cookie use as described in our Cookie Policy. You can change your cookie settings at any time by clicking âPreferences.â Preferences Accept