One place for hosting & domains

      3 Things You Should Never Outsource for Your Small Business (And 6 You Should)


      As a small business owner, there might come a point when you feel it’s time to call for backup. Perhaps you’re struggling to stay on top of your responsibilities, or you realize that you lack the required expertise to carry out certain tasks.

      In these situations, outsourcing might be the right solution for you. It involves hiring a third party to perform essential services, such as managing your company website and social media accounts. However, before getting outside assistance, it’s essential to identify the business areas that could benefit most from this strategy.

      In this article, we’ll look at the main advantages of outsourcing jobs for your small company. We’ll also highlight the three things to never outsource for your small business and the six you can definitely hand off to someone else. Let’s get started!

      The Advantages of Outsourcing for Small Businesses

      Outsourcing can be very beneficial for small business owners. For starters, hiring third parties tends to be more cost-effective than employing new staff members, mainly because you don’t have to spend money on renting office space or expanding your existing location.

      You’ll also avoid other costs that generally come with hiring employees, such as software licensing. When you outsource, you’re only paying for the services delivered by the third party.

      “An example of a small business website.”

      Outsourcing can also reduce your stress as a small business owner and help you prioritize your tasks more efficiently. As your company grows, you may find that your workload becomes unmanageable. Handing over certain jobs to third parties will free you of those unnecessary burdens, so you can focus more time and energy on developing your products or services.

      Finally, outsourcing can help you achieve your business goals more efficiently. For example, if you wish to grow your Instagram audience and drive more sales, you can achieve this quicker if you hire a social media expert (rather than doing it yourself or training an existing staff member).

      Likewise, if you want a new website, you can have one up and running within a few days if you hire a professional. Ultimately, you can use outsourcing to fill gaps in your workforce and have experts take over the weaker areas of your organization.

      How to Determine What Type of Help You Need

      Perhaps you’ve decided that outsourcing is the right option for your small business and are wondering how to determine the type of help you require. Let’s look at a few factors to consider.

      It’s best to start by identifying the tasks that are hard both for you and your team. These typically tend to be secondary or additional duties on top of primary responsibilities.

      For example, your customer service assistant might also do a bit of social media marketing when time permits, even if it’s not their area of expertise. In this case, it makes sense to outsource your social media marketing, so you’ll have someone who can dedicate more time to it and achieve better results.

      You might also want to track your time when working on particular tasks or projects. Even if you and your staff are qualified enough to handle every area of your business, some jobs can be more time-consuming than others, and in turn, require outsourcing.

      For instance, while you may have the technical expertise to manage your website, doing so could be taking up a large part of your working day. Therefore, it might be a good idea to entrust a professional with the maintenance of your company site.

      Delegate More, Stress Less

      Running a website takes work. Now you can offload backend jobs — things like performance optimization, malware removal, and updating old software — to DreamHost’s technical professionals and free yourself up to focus on your business.

      3 Things You Should Never Outsource for Your Small Business

      Outsourcing can make things easier for you and your team. However, we believe there are three areas of your business that you should avoid handing over to third parties. Let’s take a look at them.

      1. Core Competencies

      Your core competencies are the capabilities or traits that make your company stand out from the competition. For instance, your main competency could be your innovative marketing strategy, or perhaps it’s the quality and reliability of your products. In other words, it’s what makes your business special.

      Since this core competency gives you a competitive advantage, you might want to avoid assigning it to outside parties. Think of it as your ‘secret recipe’ that you want to protect and constantly improve.

      2. Customer Service

      Another area of your business that you should avoid outsourcing is customer service. When you interact directly with your clients, you can ensure that their issues and requests are addressed quickly and efficiently. This will help you earn a reputation for really caring about your user base.

      Meanwhile, when you entrust a third party with your customer support operations, it’s hard to be sure whether they are dealing with your clients professionally. Poor service can cause irreparable damage to your brand image. You can also miss out on vital information about weak areas, which can help you improve your offerings.

      3. Human Resources

      If you have a small team, handling your own human resources could be more cost-effective than outsourcing it. You may have one member of staff who has the authority to approve or reject holiday leave, deal with payroll processing, and handle other employee-related issues.

      Having an in-house human resource manager also means that any problems or conflicts within your small team can get addressed and resolved instantly. This creates a safe and supportive working environment for your employees, which can positively impact their productivity.

      6 Things You Should Consider Outsourcing for Your Small Business

      As your workload begins to increase, you may feel the need to hire more freelancers or firms to handle a specific task or business function for you. Here are six main services you should consider outsourcing if you want to save money on training and employing staff.

      1. Content Marketing

      Content marketing is about publishing material aimed at engaging people with your brand and products. This normally includes articles, videos, and social media posts.

      “A DreamHost blog post.”

      Crafting interesting content for your audience requires time and creativity. When you outsource your content marketing to a freelancer (also known as an independent contractor) or a content agency, you can have professional writers regularly creating high-quality posts for your company website or social media channels.

      Outsourcing helps ensure that you will have fresh, engaging content published regularly. In addition to continuously providing value to your clients, this can also help boost your rankings in search engines.

      2. Search Engine Optimization (SEO) Marketing

      SEO is a marketing strategy that helps your website get found by users looking for products in your niche. It can help you drive more traffic to your website, and therefore increase sales.

      However, SEO can take a while to master. There’s a lot of technical work involved and many different areas to cover, from performing keyword research to optimizing your website’s metadata. For this reason, you might want to consider hiring SEO strategists to help your website rank higher on search engines.

      3. Social Media Marketing

      Managing multiple social media accounts can be taxing. The quickest way to grow your following and engagement is to publish unique posts daily – something you and your team may not have the time for.

      “The Cluse Instagram account.”

      Outsourcing your social media marketing means you won’t have to spend hours taking beautiful photos for your Instagram account or trying to come up with interesting content to post on your Facebook page. Social media experts can do all the posting for you while helping you reach a wider audience.

      4. Website Design

      These days, almost everyone can create a website. Thanks to the variety of drag-and-drop website builders available, developing your own site has never been easier. However, not everyone is design-savvy, and a poorly-built site can drive people away.

      If you want people to trust your authority or buy your online products, your company should have a professional website. We recommend hiring web design experts who can create a stunning WordPress website that reflects your brand image and values and offers an engaging User Experience (UX).

      5. Website Management

      As a business owner, building a well-designed and functional website is just the beginning. Once you’ve set up your site, it’s essential to make sure that it’s actively managed and maintained.

      Considering that this is a time-consuming and sometimes tedious undertaking, we recommend finding someone who can manage the technical work.

      “The DreamHost Pro Services site.”

      Occasionally, your website will require some updates or backups. Moreover, some features might stop working, or your site may become unresponsive.

      If you outsource your website management, you don’t have to worry about fixing glitches on your site or resolving serious issues such as hacking attacks. Instead, you can have experts troubleshoot any technical issues and carry out regular maintenance on your site.

      6. Website Development

      As your business grows, so will your website. Perhaps you’ll need to add new products to your online shop or install new features such as live chat or a membership area.

      “A membership area of a rental property website.”

      By hiring an expert web developer, you can keep your site updated and relevant without having to do any work. Simply let your developer know what changes you want to make on your site, and they can take care of it.

      Outsource with Software and Tools

      Are you thinking of outsourcing some business operations? Consider a virtual assistant! Check out our round-up posts of software and tools that can help you manage your outsourcing:

      When hiring third parties to perform jobs for your business, it might be a good idea to use a few task management tools so you can keep track of all your outsourced projects.

      Entrepreneur Tips in Your Inbox

      Whether you need help creating the perfect web design, crafting a digital marketing strategy, or managing a remote team, we can help! Subscribe to our monthly digest so you never miss an article.

      Perfecting Your Business Process

      As your small business starts to grow, you might want to consider outsourcing some essential tasks. Hiring freelancers or other firms to take over certain areas of your business can be more cost-effective than training your team or employing new staff members.

      As discussed in this post, some areas make sense to handle in-house, such as your core competencies, customer service, and human resources. However, when it comes to marketing initiatives — such as SEO and social media and web design and development — we recommend outsourcing to minimize costs without sacrificing quality.

      If you’re looking to hand over your marketing and website management to the experts, we offer several professional services to help you grow your business in a cost-effective way. Check out our plans to learn more!



      Source link

      How to Fix 16 Common Image Issues in WordPress


      High-quality imagery can do wonders for your website. When used right, images can make your content highly engaging and easier to digest. More importantly, blog posts with images tend to rank better in search engines than those lacking visuals. Therefore, it’s essential to know how to use images on your site adequately.

      WordPress enables excellent flexibility when it comes to adding photos to pages and posts. You can format your images and arrange them within your content any way you wish. You can also make your site more visually appealing with features such as photo galleries, headers, and background images.

      If you want to learn more about using images on your WordPress site, you’ve come to the right place. In this post, we’ll show you how to fix 16 common image issues in WordPress with clear, step-by-step instructions. Let’s get started!

      We Make WordPress Easier for You

      Leave migrating your site, installing WordPress, managing security and updates, and optimizing server performance to us. Now you can focus on what matters most — growing your website!

      1. How to Upload Images in WordPress

      To upload an image in a WordPress post or page, simply click on the black button with the plus symbol (in this post, we’ll refer to it as the Add Block button). This will ask you to choose a block to insert into your content.

      Select the Image button, and a block will appear.

      Uploading an image in WordPress.

      Next, click on the Upload button and select the image you want to add. Select Open, and then you’re done!

      2. How to Align an Image to the Left or Right

      When you select an image, a toolbar will appear above it. Click on the alignment button and choose Align left or Align right.

      Aligning an image in WordPress.

      As you can see, this toolbar also gives you other options as well. This includes replacing the image and adding a link to it.

      3. How to Add Captions Below Images

      To add a caption, simply click on your image, and you’ll see the option to write something below.

      Writing an image caption in WordPress.

      Note that you’ll also get a few styling options for your caption. You can link to another page by clicking on the third button in the caption toolbar.

      4. How to Display Images in Columns and Rows

      If you want to display images in columns and rows, you can click on the Add Block button and select Gallery from the options. Next, click on Upload in the gallery block, and then select the images you want to add and choose Open.

      Adding an image gallery in WordPress.

      Once your images have been uploaded, you’ll be able to move them around. To do this, you can click on an image and use the arrow buttons. You’ll also see an option to write a caption for your images and the gallery.

      5. How to Create Responsive Image Galleries

      The default WordPress gallery is very basic. If you use your site to showcase your photography, you might want to consider adding a plugin that lets you build and customize your own image galleries.

      For beautiful responsive galleries, we recommend using the Envira Gallery plugin. After installing and activating the plugin, navigate to Envira Gallery > Add New. There you can create your first gallery, which you can then insert into your posts by selecting the Envira Gallery block.

      The Envira Gallery settings page.

      You can start by uploading some photos to your gallery and then clicking on Config to select the number of columns, set the lazy loading delay, and use the other available features.

      Adding an Envira Gallery in WordPress.

      Remember to name your galleries. This way, you’ll be able to find them more easily when adding them to your posts.

      6. How to Set Featured Images for Posts

      WordPress lets you select a featured image for your posts. This image will be attributed to your post when it appears in your blog feed. Without a featured image, your post will have a missing thumbnail image. A post thumbnail is a reduced-size picture that appears on your blog’s homepage to help users sort through and identify relevant content.

      To set a featured image, head to the sidebar on the right, select the Post tab, and navigate to the Featured image section.

      Setting a featured image in WordPress.

      Next, click on Set featured image and upload your image file. Alternatively, you can choose an image that is already uploaded to your site by clicking on the Media Library tab.

      7. How to Add Cover Images in Posts and Pages

      If you’re writing a long post, you might want to add a wide cover image between different sections so that your content is more digestible. To add a cover image, start by clicking on the Add Block button and typing “cover” into the search bar.

      Once you select the Cover button, the block will appear. Click on Upload to add an image from your computer, or select Media Library to choose an image you’ve already uploaded to your site.

      Adding a cover image in a WordPress post.

      If you want to make some changes to the cover image, you can use the options in the tool section in the post.

      8. How to Fix the Featured Image Appearing Twice

      Some WordPress themes display the featured images at the top of published posts. This image will not be visible in your post when using the content editor.

      Therefore, you might think you have to insert it into your content in addition to setting it as the featured image (as shown in step six). If you do this, you’ll get the same image twice in your live post.

      Fixing a featured image appearing twice issue.

      To fix the multiple images problem, simply delete the image from the post editor. Then you can just use the one you selected in the Set featured image box.

      9. How to Crop Images

      WordPress offers some basic photo editing features. To edit a photo, you can go to your WordPress dashboard and navigate to Media > Library. After you select the image, a window will pop up.

      Cropping images manually in WordPress.

      Click on the Edit Image button below the image, and you’ll be taken to a page with editing tools. Select the Crop button at the top, and drag the corners of the box to crop the image to your liking.

      Alternatively, you can change the image size by entering the dimensions and aspect ratio in the right sidebar.

      Cropping images in WordPress.

      At the top, you can find options to rotate and flip the image. Once you’ve finished editing your photo, click on Save. Note that the changes will be applied to the original photo.

      10. How to Add Header Images

      Some WordPress themes feature header images. To change the default header image, go to your dashboard and navigate to Appearance > Customize.

      On the customization page, click on Header Image. If you can’t see this option in the menu, it means that your current theme does not support header images.

      Changing the header of a WordPress theme.

      On the Header Image page, select Add new image to replace the default image in your header.

      Changing the header of your WordPress site.

      When you’re done, you can click on the Publish button at the top of the screen. This will save your changes.

      11. How to Add Background Images

      Your WordPress theme might also come with support for background images. To set a one, access the theme’s customization page by navigating to Appearance > Customize from your WordPress dashboard.

      Next, click on Colors. Locate Body Background and click on Select image.

      Changing the background of your WordPress site.

      When you set your background image, you’ll get some options for adjusting the preset and image position. Remember to save your changes before exiting.

      12. How to Find Free Images for Your WordPress Site

      When sourcing images for your posts and pages, we recommend accessing free stock photo sites to avoid copyright infringement. Several sites offer royalty-free images, including Pixabay, UnsplashFlickr Creative Commons, and Pexels.

      A site offering free stock photos.

      The images available on these sites are free to use. However, it’s always a good idea to credit the photographer or artist with a link in the image caption.

      13. How to Tag Images

      Tags make it easier to organize and filter photos on your site. However, WordPress currently does not offer an image tagging feature. Therefore, you might want to download a plugin that lets you sort your images with categories and tags.

      For categorizing and tagging images, we recommend using the Media Library Assistant plugin. Start by installing and activating the plugin, and then head to Media > Library.

      You can see all the photos you’ve uploaded to your WordPress site on the Media Library page. Click on the list view button at the top, then find the photo you want to tag and click on Edit.

      The WordPress Media Library.

      On the Edit Media page, find the Att. Categories and Att. Tags sections on the right-hand side, and start adding categories and tags to your image.

      Tagging images in WordPress.

      You can also rename your image on this page, write a caption, and add alternative text. When you’re done, click on the Update button on the right to save your changes.

      14. How to Import External Images to WordPress

      To import external images to WordPress, you’ll need to access your old website’s files directly using a Secure File Transfer Protocol (SFTP) tool such as FileZilla. Locate your site’s root directory, and then go to wp-content/uploads.

      Accessing the WordPress uploads folder.

      There, you’ll find the media files that you’ve uploaded to your site. Download them to a secure location, and then log into your new WordPress site. Navigate to wp-content/uploads again, and copy over your media files.

      You may still encounter image-related errors after doing this since your image URLs may be pointing back to your old site. If that’s the case, you’ll need to go through and update your image URLs so they point to your new site instead, which can be a time-consuming process.

      To avoid that problem, we recommend using a plugin such as Duplicator to move your website between domains or web hosts. You may also benefit from reaching out to your new host for assistance to make sure everything on your site gets transferred over properly.

      15. How to Require a Featured Image in Your Posts

      If your site has multiple authors, you might want to set a reminder for everyone to select a featured image before publishing a post. To do this, you’ll need to add some custom code to your site.

      Before getting started, we recommend backing up your site and creating a child theme. Then you can add the following code at the end of your theme’s functions.php file:

      <?php
      
      /**
      
      * Require a featured image to be set before a post can be published.
      
      */
      
      add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
      
      $post_id              = $postarr['ID'];
      
      $post_status          = $data['post_status'];
      
      $original_post_status = $postarr['original_post_status'];
      
      if ( $post_id && 'publish' === $post_status && 'publish' !== $original_post_status ) {
      
      $post_type = get_post_type( $post_id );
      
      if ( post_type_supports( $post_type, 'thumbnail' ) && ! has_post_thumbnail( $post_id ) ) {
      
      $data['post_status'] = 'draft';
      
      }
      
      }
      
      return $data;
      
      }, 10, 2 );
      
      add_action( 'admin_notices', function () {
      
      $post = get_post();
      
      if ( 'publish' !== get_post_status( $post->ID ) && ! has_post_thumbnail( $post->ID ) ) { ?>
      
      <div id="message" class="error">
      
      <p>
      
      <strong><?php _e( 'Please set a Featured Image. This post cannot be published without one.' ); ?></strong>
      
      </p>
      
      </div>
      
      <?php
      
      }
      
      } );

      Save your changes, and users will be required to add featured images to all post types that support them.

      16. How to Set a Default Featured Image

      If you want to set a default featured image for those occasions when you can’t find the right photo, the Default Featured Image plugin is a handy tool to have. It lets you choose a photo that will automatically appear as the featured image for posts published without one.

      After installing and activating the plugin, navigate to Settings > Media in your dashboard.

      Using the Default Featured Image plugin.

      Click on the Select default feature image button and choose your photo. Finally, hit Save Changes at the bottom of the page.

      Take Your WordPress Website to the Next Level

      Whether you need help navigating the WordPress dashboard, choosing the perfect product image, or writing alt text, we can help! Subscribe to our monthly newsletter so you never miss an article.

      Additional WordPress Resources

      If you’re new to WordPress, you may run into some common issues while working with images and other content. To help you navigate any WordPress problem you encounter, we’ve put together several how-to guides:

      If you’re looking for more WordPress tips and hacks, check out our WordPress Tutorials. This collection of guides will help you set up and design your first WordPress site.

      Now You Can Fix That Common Image Issue

      Images can improve your site’s User Experience (UX) and increase the visibility of your content in search engine results. Therefore, it’s important to know how to use photos to engage readers with your content.

      Fortunately, WordPress makes it easy to upload and manage photos on your site. It lets you crop and customize images, as well as create beautiful photo galleries and headers to make your pages more interesting.

      If your business relies on high-quality imagery, you might want to consider using a web hosting service that offers full WordPress support. Our DreamPress plans are perfect for site owners who want to focus on growing their businesses and spend less time troubleshooting errors in WordPress.



      Source link

      How To Create User Interactions with Events in Vue


      The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.

      Introduction

      In Vue.js development, a client’s web browser reads HTML and JavaScript and renders web pages based off of the instructions that the developer writes for it. But the web page or application not only needs to process data; it also needs to process user interactions. To do this, developers use events in JavaScript that execute code when the user interacts with HTML elements.

      An event can capture any user interaction with a user interface button or a physical keyboard or mouse. In JavaScript, you would create event listeners that wait for that event to occur and then execute a block of code. In Vue.js, you are not required to listen for an event; that is done automatically with the v-on: directive.

      In this tutorial, you will use events in Vue to create an application of airport codes. When the user selects an airport code, the app will add that airport to a “favorites” collection. By following along with this project, you will learn what events are, how to use Vue’s built-in events, and how to create your own custom events.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Setting Up the Project

      The first step in this tutorial will be to set up a demo project with some data to display in the view. This will include an array of JavaScript objects that contain airport data and a Vue component to iterate over and render the data.

      First, generate a project using Vue CLI:

      • vue create favorite-airports

      This will create a project named favorite-airports. This tutorial will use Vue 3, so when prompted, select the option Default (Vue 3) ([Vue 3] babel, eslint):

      Output

      Vue CLI v4.5.6 ? Please pick a preset: Default ([Vue 2] babel, eslint) ❯ Default (Vue 3) ([Vue 3] babel, eslint) Manually select features

      Once you have created the project, make a directory to hold all of your local data for this project. First, make the new project folder your working directory:

      Next, make a data directory in the src directory:

      In your text editor of choice, open a file called src/data/airports.js. Add the following data to the file:

      favorite-airports/src/data/airports.js

      export default [
        {
          name: 'Cincinnati/Northern Kentucky International Airport',
          abbreviation: 'CVG',
          city: 'Hebron',
          state: 'KY',
        },
        {
          name: 'Seattle-Tacoma International Airport',
          abbreviation: 'SEA',
          city: 'Seattle',
          state: 'WA',
        },
        {
          name: 'Minneapolis-Saint Paul International Airport',
          abbreviation: 'MSP',
          city: 'Bloomington',
          state: 'MN',
        },
        {
          name: 'Louis Armstrong New Orleans International Airport',
          abbreviation: 'MSY',
          city: 'New Orleans',
          state: 'LA',
        },
        {
          name: `Chicago O'hare International Airport`,
          abbreviation: 'ORD',
          city: 'Chicago',
          state: 'IL',
        },
        {
          name: `Miami International Airport`,
          abbreviation: 'MIA',
          city: 'Miami',
          state: 'FL',
        }
      ]
      

      This data is an array of objects consisting of a few airports in the United States. Next, you are going to iterate through this data to generate cards consisting of the name, abbreviation, city, and state properties. When the user clicks on a card, the app will emit an event up to the parent, which will add that airport to a collection of data that will represent your favorite airports.

      Save and close the airport.js file.

      To render the data, create a single-file component (SFC) with the name src/components/AirportCard.vue and open it in your text editor. This component will contain all of the styles and logic for the airport card.

      Add the following contents to the file:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      
      <script>
      export default {
        props: {
          airport: {
            type: Object,
            required: true
          }
        }
      }
      </script>
      
      <style scoped>
      .airport {
        border: 3px solid;
        border-radius: .5rem;
        padding: 1rem;
      }
      
      .airport p:first-child {
        font-weight: bold;
        font-size: 2.5rem;
        margin: 1rem 0;
      }
      
      .airport p:last-child {
        font-style: italic;
        font-size: .8rem;
      }
      </style>
      

      This component contains a prop, which in Vue.js is a way to pass data down from a parent component to a child component. The template section then renders this data. For more on single-file components, check out the How To Create Reusable Blocks of Code with Vue Single-File Components tutorial.

      You may notice that there is some CSS included in the code snippet. In the AirportCard.vue component, the wrapper <div> contains the class of airport. This CSS adds some styling to the generated HTML by adding borders to give each airport the appearance of a card. :first-child and :last-child are pseudo-selectors that apply different styling to the first and last p tags in the HTML inside of the div with the class of airport.

      Save the file and exit from your text editor.

      Next, modify the existing App.vue component to iterate through the airports.js data and render a series of AirportCards.vue components. Open src/App.vue in your text editor and replace the contents with the following highlighted code:

      favorite-airports/src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation">
            <airport-card :airport="airport" />
          </div>
        </div>
      </template>
      
      <script>
      import { ref } from 'vue'
      import allAirports from '@/data/airports.js'
      import AirportCard from '@/components/AirportCard.vue'
      
      export default {
        components: {
          AirportCard
        },
        setup() {
          const airports = ref(allAirports)
          return { airports }
        }
      }
      </script>
      
      <style>
      #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
      }
      
      .wrapper {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 1rem;
        max-width: 960px;
        margin: 0 auto;
      }
      </style>
      

      This imports the data and the SFC, then uses the v-for directive to iterate over the data, creating an airport card for each object in the airport.js array. It also adds additional CSS targeted to the wrapper class, which uses CSS grid to manage the layout of the cards.

      Save and exit the file. With the project now set up, run a local development server with the following command:

      This will start a server on your localhost, usually on port :8080. Open your web browser of choice and visit localhost:8080 to find the following:

      A view of the airport data rendered on cards, with the airport abbreviation, full name, and location rendered in black, sans-serif font.

      Now that you have your sample project set up, you’ll next explore built-in events using the v-on directive. When this event is fired, an alert pop-up box will appear with the airport code of the airport associated with that event.

      Step 2 — Listening for Events With the v-on Directive

      As stated earlier, events are a way to execute functions when the user interacts with HTML elements in the DOM (Document Object Model). When writing vanilla JavaScript, to execute a function on an event, you may write something called an event listener. An event listener is a function that waits for that interaction to occur, then executes some code. With Vue, however, you can use the v-on directive for this purpose. A directive is a piece of re-useable code that a developer can use in order to manipulate the DOM. The v-on directive is provided by Vue.js out of the box.

      In this step, you will create a function in your application that runs when a user clicks on a card. Open the src/components/AirportCard.vue component in your text editor of choice.

      Create a function that alerts the user of the airport that they clicked on by adding the following highlighted code:

      favorite-airports/src/components/AirportCard.vue

      ...
      <script>
      export default {
        props: {
          airport: {
            type: Object,
            required: true
          }
        },
        setup() {
          function selectAirport(airport) {
            alert(`You clicked on ${airport.abbreviation}. It's located in ${airport.city}, ${airport.state}.`)
          }
      
          return { selectAirport }
        }
      }
      </script>
      ...
      

      In Vue.js 3, reactive functions need to be defined and exported in the setup component method. This tells Vue that it can execute the selectAirport function in the <template>.

      With the function defined, you’ll now attach it to an event on an HTML element. As stated before, you can use the v-on directive and attach an event with the name of click; this is an event provided by Vue.js. In the AirportCard.vue component, add the v-on directive to the wrapper <div>:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport" v-on:click="selectAirport(airport)">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      ...
      

      Once you have added this code, save and exit the file.

      Now, when you click on a card, an alert will pop-up with the message provided. If you click on CVG for example, you will find the following:

      Vue site with alert pop-up that reads "localhost:8080 says You clicked on CVG. It's located in Hebron, KY."

      The click event is not the only event that is provided to you out-of-the-box by Vue.js. In fact, you can use v-on any native JavaScript event, like:

      • keyup
      • mouseover
      • focus
      • mouseenter
      • change

      Next, you will change this v-on:click listener to mouseover to illustrate how Vue.js listens for events. mouseover is an event that fires whenever a mouse cursor moves over an HTML element.

      Open up src/components/AirportCard.vue again and update your file with the following highlighted code:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport" @mouseover="selectAirport(airport)">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      

      As shown here, Vue also has shorthand syntax for v-on: events. To use the shorthand syntax, you replaced v-on with @. Save and exit the file.

      Now when you visit localhost:8080 and hover over a card, that function will execute and display a native alert.

      This functionality is good for testing purposes, but may be undesired since it displays the alert every time a user hovers over it. A better experience might be to only display it the first time a user hovers over that card. In vanilla JavaScript, you may track the amount of times a user hovers over a card, then prevent further executions. Vue.js has event modifiers that you can leverage to accomplish the same thing with less code.

      In the next section, you are going to explore event modifiers and use them for a better user experience.

      Step 3 — Using Event and Key Modifiers

      In the previous section, you executed a function on the click and mouseover events. You also learned about the Vue.js shorthand for v-on events. Now you will expand on this further by attaching a modifier to this mouseover event so your function executes only once.

      Vue.js provides a number of event modifiers for you. Some of these include:

      • .stop: stops event propagation
      • .prevent: prevents the HTML element’s default behavior
      • .capture: handles an event targeting an inner element before the selected element
      • .self: only triggers the handler if event.target is the element itself
      • .once: only executes the function once
      • .passive: enables the element’s default behavior to happen immediately instead of waiting for the event, which can be used for optimizing performance for scroll on mobile devices

      In this case, you’ll use the .once modifier. In your text editor, open the AirportCard.vue component and add the modifier to the existing mouseover event:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport" @mouseover.once="selectAirport(airport)">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      

      Save the file. Visit your application in the browser and you’ll find that the event only fires once on the first mouseover event.

      Next, you’ll continue exploring modifiers by using key modifiers. These key modifiers are associated with keystroke events, such as keyup. For this next part, imagine that you want to make this clicking action a little more explicit. One way you can do that is by adding a key modifier to the @click event on the .airport <div> in your template.

      To do that, change the @mouseover to @click and add the .shift modifier:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport" @click.shift="selectAirport(airport)">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      

      Save the changes and open the application in your browser. If you click on a card without holding the SHIFT key, the alert does nothing. Now, try holding down the SHIFT key when clicking on a card. Your function will now execute, and you will receive an alert.

      In this section, you learned about Vue’s built-in events and the modifiers associated with those events. You can get a lot done with these built-in events, but there will be times when you’ll need to have a custom event. In the next section, you’re going to use custom events to emit an action up to a parent so that it will execute a function.

      Step 4 — Creating Custom Events

      When developing applications in Vue.js, there will be times when you need to pass data up to a parent component via a custom event. Props are read-only data that are passed down to a child from the parent, but a custom action via an $emit is the opposite of that. To create the most reusable components, it’s best to think of these as functions. You pass data down through props (arguments), and emit values back up to the parent (a return value).

      To emit an event from the child component to the parent, you use the $emit function. Before implementing this, this tutorial will guide you through an example to demonstrate how this works.

      The $emit function accepts two arguments: the action name (a string), and the value to pass up to the parent. In the following example, when the user clicks on the button, you are sending the value CVG to the parent component under the action favoriteAirport:

      ChildComponent.vue

      <template>
        <button @click="$emit('favoriteAirport', 'CVG')">A button</button>
      </template>
      

      In the parent component, you would use the v-on directive and listen for the favoriteAirport event. When this custom event is fired, the code will do something with the value:

      ParentComponent.vue

      <template>
        <child-component @favoriteAirport="favoriteAirport = $event" />
      </template>
      
      <script>
      import { ref } from 'vue'
      export default {
        setup() {
          const favoriteAirport = ref('')
      
          return { favoriteAirport }
        }
      }
      </script>
      

      The value of the event will be $event. In this case, $event is actually CVG, which you then store in a reactive data property called favoriteAirport.

      Now that you know what a custom event looks like, you will put it into practice by implementing this custom event into your application.

      Open the AirportCards.vue component in your text editor. In the @click event, remove the reference to the function and replace it with $emit("favoriteAirport", airport). Remember, the first arugment is the name of the event and the second is the value that you are emitting:

      favorite-airports/src/components/AirportCard.vue

      <template>
        <div class="airport" @click="$emit('favoriteAirport', airport)">
          <p>{{ airport.abbreviation }}</p>
          <p>{{ airport.name }}</p>
          <p>{{ airport.city }}, {{ airport.state }}</p>
        </div>
      </template>
      ...
      

      Save the file. Now, when the user clicks on the airport card, a custom event will fire and pass up that airport object.

      Next, open src/App.vue to add some HTML to the template. You will show the favorite airports list after the six cards that are already present:

      favorite-airports/src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation">
            <airport-card :airport="airport" />
          </div>
          <h1 v-if="favoriteAirports.length">Favorite Airports</h1>
          <div v-for="airport in favoriteAirports" :key="airport.abbreviation">
            <airport-card :airport="airport" />
         </div>
        </div>
      </template>
      
      <script>
      import { ref } from 'vue'
      import allAirports from '@/data/airports.js'
      import AirportCard from '@/components/AirportCard.vue'
      
      export default {
        components: {
          AirportCard
        },
        setup() {
          const airports = ref(allAirports)
          const favoriteAirports = ref([])
      
          return { airports, favoriteAirports }
        }
      }
      </script>
      ...
      

      In this code snippet, you are creating a reactive data property called favoriteAirports, which is an empty array. In the <template>, you iterate through the empty array to render the <airport-card /> components, much like you did in an earlier step.

      Now you need to add the v-on event for your custom event:

      favorite-airports/src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation">
            <airport-card :airport="airport" @favoriteAirport="favoriteAirports.push($event)" />
          </div>
          <h1 v-if="favoriteAirports.length">Favorite Airports</h1>
          <div v-for="airport in favoriteAirports" :key="airport.abbreviation">
            <airport-card :airport="airport" />
         </div>
        </div>
      </template>
      ...
      

      In the @favoriteAiport custom event, you used the JavaScript push() method to add the airport from the child ($event) to the favoriteAirports reactive data property.

      Open you browser and navigate to your project at localhost:8080. When you click on one of the airport cards, that card will appear under Favorite Airports.

      Vue airport app with a list of favorite airports that includes the CVG airport card.

      In this section, you learned about custom events, what they are, and how to use them. A custom event is a way to pass data up to a parent component through the $emit function provided by Vue. Once that data has been emitted, you can further manipulate it in the parent component, like adding it to an array.

      Conclusion

      In this tutorial, you learned how Vue.js listens for a number of built-in events, such as click and mouseover. In addition to that, you tried out event and key modifiers, small pieces of code that you appended to your event to provide additional functionality. With this, you set up your app to execute the function once with the .once modifier and to only fire when holding down the SHIFT key using the .shift modifier.

      Vue provides an efficient way to listen for events that lets you focus on manipulating data over manually setting up event listeners. In addition to that, Vue allows you to think of components as functions: They accept data props and can return a value with $emit.

      To learn more about Vue components, it is recommended to read through the Vue documentation. For more tutorials on Vue, check out the How To Develop Websites with Vue.js series page.



      Source link