One place for hosting & domains

      June 2021

      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

      How To Install the Windows Subsystem for Linux 2 on Microsoft Windows 10


      Introduction

      The Windows Subsystem for Linux 2, WSL 2 or WSL for short, is a tool on Microsoft Windows 10 that allows developers to run a Linux environment directly on Windows without any modifications, secondary Virtual Machine software, or dual-boot setups. The WSL natively integrates with most applications on your workstation, allowing for a Linux-like development experience on Windows. The WSL accomplishes this by using Microsoft’s built in virtualization software called Hyper-V to run.

      In this tutorial you’ll enable the WSL, install Ubuntu 20.04 onto your workstation using the WSL, and install Microsoft’s new Windows Command Line to access your Ubuntu 20.04 installation. This will provide you with a Linux programming environment that is native to Windows.

      Prerequisites

      In order to follow along with this guide, you’ll need:

      • Personal Computer with Windows 10 installed: The Windows Subsystem for
        Linux 2 requires Windows 10 version 1903 or higher with build 18362 or higher. For ARM64 systems, version 2004 or higher with build 19041 is required. Builds lower than this will not support the WSL 2.

      Warning: If you are installing the WSL on a virtual machine you will need to expose CPU virtualizations flags to the virtual machine. For example, if you are installing the WSL on a virtualized Windows 10 that is running in Hyper-V named MyWSL you will need to run the following command on the virtualization host, not the virtual machine. This is a Windows command so you will need an elevated PowerShell prompt to do this. Replace MyWSL with the name of your VM in Hyper-V:

      • Set-VMProcessor -VMName MyWSL -ExposeVirtualizationExtensions $true

      If you are not installing the WSL on a virtual machine, you can skip this warning entirely.

      Step 1 — Enabling Windows Services for the WSL

      The first thing you need to do is enable specific Windows services so that you can run the WSL. These services come with Windows but are turned off by default until you decide you need them. Open up the Start menu and search for PowerShell. You’ll need to right click on PowerShell and click on Run as Administrator.

      Open Windows PowerShell as an administrator

      Once you’ve done this, a PowerShell window will open. You’ll use the Windows Deployment Image Servicing and Management tool to enable optional Windows features that are disabled by default. Run the following command to enable the WSL feature:

      PS C:Windowssystem32> dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
      

      Once you run the command you’ll see output similar to this:

      output

      Deployment Image Servicing and Management tool Version: 10.0.19041.844 Image Version: 10.0.19042.985 Enabling feature(s) [==========================100.0%==========================] The operation completed successfully.

      Next, run the following command in PowerShell to enable Windows’ Virtual Machine Platform. This enables the second generation of the WSL by enabling Hyper-V and allowing Windows’ to install Linux using it.

      PS C:Windowssystem32> dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
      

      Once you run the command you’ll see output similar to this:

      output

      Deployment Image Servicing and Management tool Version: 10.0.19041.844 Image Version: 10.0.19042.985 Enabling feature(s) [==========================100.0%==========================] The operation completed successfully.

      Once you have done this you will need to restart Windows for these changes to take place.

      After the restart is finished, log back in to your workstation.

      Next you’ll need to download the latest Linux kernel update package from Microsoft and install it.

      To install this package, click to download the wsl_update_x64.msi package to your local workstation. Once it is downloaded, run the application and follow the prompts to install it.

      Download the Linux Kernel patch and run

      Finally, you need to set the default version of the WSL to version 2. Open another PowerShell terminal as an administrator and run the following command:

      PS C:Windowssystem32> wsl --set-default-version 2
      

      Once you run the command you’ll see output similar to this:

      output

      For information on key differences with WSL 2 please visit https://aka.ms/wsl2

      Now that you’ve done this the WSL 2 is enabled and ready to run on your workstation. Next you’ll need to install a Linux-based operating system using the WSL 2.

      Step 2 — Installing Ubuntu 20.04 using the WSL

      Now that you have the WSL 2 installed, you next need to install a Linux distribution from the Microsoft Store. For this tutorial we will be installing the default Ubuntu option from the store, which happens to be Ubuntu 20.04 at this time. There are many different options to choose from and all should take a nearly identical approach to installation as laid out in this tutorial.

      Open your Start menu, search for the Microsoft Store, and open it.

      Open the Microsoft Store

      Locate the search bar in the upper right-hand corner and search for Linux.

      Search for Linux

      Many options will appear; select the Ubuntu tile to install the latest supported version of Ubuntu. Click the Get button to add the app to your account. Once you’ve done this, the Get button will be replaced by the Install button. Click that button to install Ubuntu to your local workstation. Once the installation is done a Launch button will appear. Click this to launch Ubuntu.

      Select Ubuntu and Install

      The first time you launch Ubuntu it will inform you that it is performing initial configuration that may take a few minutes. After this it will prompt you for a Linux system username and password. This username and password doesn’t have to be the same as your system but it will be required for you to be able to use sudo to gain admin privileges.

      Perform Initial Setup of Ubuntu

      Once you have created your user the initial setup is complete and Ubuntu is ready to be used.

      Once initial setup is done Ubuntu is ready to be used

      Now that you have Ubuntu installed, you’ll install a more robust terminal for accessing Ubuntu through Windows.

      Step 3 — Installing and Configuring the New Windows Command Line

      Ubuntu provides a default terminal for use, but Microsoft open sourced and reimplemented their Terminal tool and branded it at Windows Terminal. This terminal supports many more customization and ease-of-use options than the default Ubuntu terminal, so you’ll want to install it.

      Next you’ll install this terminal on your workstation. Navigate back to the search bar in the Microsoft Store and search for Terminal.

      Search Terminal in the Microsoft Store looking for Windows Terminal

      Install the Windows Terminal the same way you installed Ubuntu, by clicking Get and Install. Launch the terminal by clicking Launch or selecting the program from your Start menu.

      Get and Install the Windows Terminal. Then click launch

      By default, the Windows Terminal opens up a PowerShell console.

      Default Windows Terminal opens up PowerShell

      If you want to open a different console, click the down arrow button to see what is available. You have access to PowerShell, Command Prompt, and Azure Cloud Shell by default. When you install any WSL Linux, it will appear here as well like the Ubuntu install did. Clicking Ubuntu will open an Ubuntu shell in a new tab.

      Windows Terminal supports many different options

      If you want to change some of the Terminal’s default options, click the down arrow button and select Settings.

      Open up settings to change the default to the WSL Ubuntu

      Next, set Ubuntu as your default console. Under Default Profile select your Ubuntu WSL image, and click Save to make it your default option.

      Select Ubuntu as your Default Profile

      Now when you click the + button or open a new terminal Ubuntu will be the default shell.

      Clicking the plus or opening the terminal new will give you your WSL Ubuntu shell

      You now have the new Windows Command Line tool installed and configured to open your WSL Ubuntu terminal by default. You are now ready to use Linux on Windows using the WSL.

      Conclusion

      You now have a fully functioning Linux environment running in Windows. You configured your computer to take advantage of the Windows Subystem for Linux, and installed an Ubuntu environment using the WSL. If you prefer a different Linux distribution, there are others you can install, including Debian, SUSE, or Kali Linux. From here, you can install developer tools to have a complete Linux development environment running on Windows.



      Source link