One place for hosting & domains

      User

      SQL Security and User Management


      User management and permissions are essential to SQL database security. Typically, SQL database security schemes consist of one or more users, their authentication, and permissions. The database engine validates a user’s permissions when they attempt to perform an operation against a SQL object —for example, a table, an index, a stored procedure, etc. The basic premise behind the assignment of SQL roles and permissions is to provide users of the database access to only what is necessary to perform their job. In this guide, you learn how to create and assign roles and permissions to users of relational database systems.

      Users and Groups

      In order to grant access rights and permissions, a relational database management system requires user identities.
      These rights and permissions can be assigned to either an individual user, or a group of users. If you have more than one user with similar access requirements and restrictions, you can define a group. Then, you add the collective set of users as members of the appropriate group. In this way, the authentication and validation process for a given SQL object is applied against the group instead of the user. This assumes that no restrictions have been established for individual users. In the case where a user and the user’s group both have access restrictions on a given SQL object, the database applies the most restrictive access rights of either the user or the user’s group.

      Roles

      Users of relational database systems are typically assigned roles. Different users might need to perform different tasks on the same database. For example, one user might be in charge of data entry, another user might be the database administrator, and an end-user may only need to retrieve data from the database. Typically, users that have the same type of role in an organization require the same type of database access. Each database role can have its own data access permission levels. Once the role is created and the appropriate permissions are applied, you can add individual users to that role. All users assigned to a particular role inherit its permissions.

      Permissions

      There are two different types of permissions that can be assigned to roles, users, and groups: statement permissions and object permissions. Statement permissions grant access to execute specific statements against a database. For example, a user could be granted access to create a stored procedure, but not be granted the right to create tables. Object permissions, on the other hand, grant the user the right to access a database object such as a table, a view, or to execute a stored procedure.

      Implementation of Users, Groups, Roles, and Permissions

      When it comes to the management of users, groups, roles, and permissions, the concepts stated in the previous sections are quite uniform across SQL-based database management systems. What may differ are the names of commands and the syntax used by different SQL database implementations.

      Note

      The examples below use Microsoft SQL Server syntax. All commands should be executed from the command line. The examples also assume that all server security hardening has already been implemented.

      To demonstrate SQL security principles, this guide uses an example database that is used by a school. The school’s database has tables for students and courses taken by each student. The definition of the Student table contains columns for the student’s SSNumber, Firstname, and Lastname, and the definition of the CourseTaken table contains columns for SSNumber, CourseId, NumericGrade, and YearTaken.

      The example further assumes that four employees in the school administer the school database. Their respective roles are defined as follows:

      Name Database Role
      Tom Database Administrator
      John Database Data Entry
      Mary Database Query and Reports
      Joan Database Query and Reports

      In the example below, assume that Tom, the database administrator (DBA), has created the school database via the CREATE DATABASE command:

      CREATE DATABASE School;
      

      Next, Tom creates database user login definitions for all four employees (including themselves) via the CREATE USER command:

      Use School;
      CREATE USER Tom WITH PASSWORD = 'Tompassword';
      CREATE USER John WITH PASSWORD = 'Johnpassword';
      CREATE USER Mary WITH PASSWORD = 'Marypassword';
      CREATE USER Joan WITH PASSWORD = 'Joanpassword';
      
      CREATE USER Tom IDENTIFIED BY 'TomPassword';
      

      After creating user login definitions, Tom creates generic roles that will later be assigned to each employee, by using the CREATE ROLE command:

      USE School;
      CREATE ROLE DBAdmin;
      CREATE ROLE DataEntry;
      CREATE ROLE QueryReports;
      

      Now that the roles exist, Tom assigns the roles to the appropriate users with the ALTER ROLE command as follows:

      USE School
      ALTER ROLE DBAdmin ADD MEMBER Tom;
      ALTER ROLE DataEntry ADD MEMBER John;
      ALTER ROLE QueryReports ADD MEMBER Mary;
      ALTER ROLE QueryReports ADD MEMBER Joan;
      

      The workflow demonstrated in this section reflects the user management steps a DBA might need to take when configuring a newly created database.

      Granting Permissions

      The GRANT statement is used to assign permissions to a user or to a role. You can also use the GRANT statement to assign specific statement permissions to a user or to a role. Some of the statement permissions that can be granted are: CREATE DATABASE, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.

      For example, to grant the CREATE PROCEDURE statement permission to a user or a role, use the following command:

      GRANT CREATE PROCEDURE TO <User or Role>;
      

      Continuing along with this guide’s school database example, you can grant various permissions to the database roles you created in the previous section. Tom first grants required privileges to the DBAdmin Role (Tom’s role), via the GRANT command, as follows:

      USE School;
      GRANT CREATE DATABASE TO DBAdmin;
      GRANT CREATE RULE TO DBAdmin;
      GRANT CREATE TABLE TO DBAdmin;
      GRANT CREATE VIEW TO DBAdmin;
      GRANT DUMP DATABASE TO DBAdmin;
      GRANT DUMP TRANSACTION TO DBAdmin;
      

      Now, Tom can create the two tables in the school’s database as follows:

      USE School;
      CREATE TABLE Student (
        SSNumber CHAR(9) NOT NULL,
        LastName VARCHAR(30) NOT NULL,
        FirstName VARCHAR(20) NOT NULL
      );
      
      CREATE TABLE CourseTaken (
        SSNumber CHAR(9) NOT NULL,
        CourseId CHAR(6) NOT NULL,
        NumericGrade TINYINT NOT NULL,
        YearTaken SMALLINT NOT NULL
      );
      

      Tom grants necessary database entry permissions (INSERT, UPDATE, DELETE) on both database tables, to employee John (DBEntry role), as follows:

      USE School;
      GRANT INSERT, UPDATE, DELETE ON Student TO DBEntry;
      GRANT INSERT, UPDATE, DELETE ON CourseTaken TO DBEntry;
      

      Note

      After executing the above GRANT commands, John is permitted to INSERT, UPDATE, and DELETE data in the two database tables, but is not permitted to read (SELECT) from it.

      Tom grants necessary database read permission (SELECT) on both database tables, to employees Mary and Joan, via the QueryReports role, as follows:

      USE School;
      GRANT SELECT ON Student TO QueryReports;
      GRANT SELECT ON CourseTaken TO QueryReports;
      

      Note

      After executing the above GRANT commands, Mary and Joan can only read the database tables (via the SELECT statement), but cannot manipulate the data (via the INSERT, UPDATE, or DELETE statements).

      Revoking Permissions

      Revoking permissions is the converse of granting permissions on database objects. You can revoke permissions from a table, view, table-valued function, stored procedure, and many other types of database objects.

      Continuing with the school database example, assume that John switches his role at the school from performing data entry to querying reports. Due to this change, John should no longer have the ability to manipulate data (INSERT, UPDATE, DELETE) in the school tables. John should also be granted the ability to read data from the table (via SELECT). Tom, the database administrator, needs to execute the following commands to revoke and grant the appropriate permissions to John:

      USE School;
      REVOKE INSERT, UPDATE, DELETE ON Students FROM John;
      REVOKE INSERT, UPDATE, DELETE ON CourseTaken FROM John;
      GRANT SELECT ON Student TO John;
      GRANT SELECT ON CourseTaken TO John;
      

      Alternatively, a simpler approach is to remove John from the DBEntry role and add him to the QueryReports role:

      USE School;
      ALTER ROLE DBEntry DROP MEMBER John;
      ALTER ROLE QueryReports ADD MEMBER John;
      

      Conclusion

      User management, permissions, and roles are essential to SQL database security. Create a new group and add users to that group if they require the same database access and permissions. To control access by the tasks users should be allowed to perform against a database, use database roles.

      In SQL databases, every action must pass through a validity check that determines if the database action can be completed by a particular user. The appropriate permissions are required to access SQL database objects and execute statements. The integrity of a SQL database relies on secure and well-designed user management.

      Now that you are familiar with SQL user management, you can learn about some different aspects of the SQL language, like
      joins
      ,
      data types
      , and
      grouping and totaling
      .



      Source link

      The Ultimate Guide to WordPress User Roles


      WordPress is a powerful, flexible Content Management System (CMS) that can be an excellent solution for collaboration. However, to make the most of the CMS, it’s important to understand how to navigate and leverage its user roles and permissions features.

      WordPress user roles let you assign certain levels of access to people who are registered to your website. This can help you manage and control what tasks are possible and can ultimately help strengthen your site’s security and performance.

      In this post, we’ll explain what WordPress user roles and permissions are. Then, we’ll provide you with advice for assigning them and cover some helpful troubleshooting tips and useful plugins to help you manage your users. Let’s get started!

      An Introduction to WordPress User Roles and Permissions (And Why They’re Important)

      WordPress user roles and permissions are two different but interdependent concepts. User roles determine what a user can and can’t do on your WordPress site, based on their user type. These limitations are generalized for anyone who carries a certain user role status.

      Permissions, on the other hand, are more individualized. You can create custom permissions for specific users, and control exactly what they are allowed to do on your site. Moreover, you can give different users distinct permissions depending on their role.

      With this double-layered system, you can ensure that each user only sees and accesses the features that are appropriate for them. Furthermore, you can create custom roles with unique capabilities, which is a great way to provide additional functionality for advanced users or clients who need certain abilities not available in the default roles.

      Both user roles and permissions are set by the Administrator, which is typically the WordPress site owner. By default, there are six different user roles: Super Admin, Administrator, Editor, Author, Contributor, and Subscriber. Each role has its own set of capabilities, which we’ll discuss in more detail below.

      User roles and permissions play an important role in ensuring that your WordPress website is secure and runs smoothly. By managing these settings, you can control who has access to what areas of your site, and what they can do there.

      If someone has too many privileges, they can end up publishing low-quality content or changing settings that impact the functionality or appearance of your site. The good news is that when you implement user roles and capabilities, you can have peace of mind knowing that only trusted parties have full admin access.

      An Overview of the Default User Roles in WordPress

      Now that you know a bit about the importance of user roles, let’s take a closer look at the six default user roles you can choose from when managing your WordPress website. Keep in mind that as an Administrator, you have the ability to create new user roles and assign them to specific users on your site. You can also manage permissions for existing user roles.

      Super Admin

      The Super Admin is the highest level of user on a WordPress site. This user has complete control over the site, including the ability to add and delete users, install and activate plugins, manage themes, and more. Super Admins are typically only found on multisite installations of WordPress.

      Super Admins can manage every setting and feature for each site within a multi-site network. They can add and delete other Administrators, create new sites, and control content across each site.

      Administrator

      Administrators have complete control over a single WordPress site. They can add and delete users, install and activate plugins, manage themes, etc. Usually, they are the site owners or main authors:

       

      WordPress Dashboard

      This powerful role has complete access to content, features, and site settings. They can update the CMS as well as plugins and themes. The Admin is also responsible for assigning user roles and capabilities to other registered users. Ideally, you should only have one Administrator per website.

      Editor

      Editors can manage and publish posts and pages, as well as moderate comments. They can also schedule content and edit categories. However, they cannot install or activate plugins, or manage themes:

      WordPress Dashboard

      In a nutshell, an editor can modify content created by themselves and other users with a lower status, such as Authors and Contributors. They can’t change content for users with permissions higher than theirs, such as an Administrator. Typically, this role is reserved for content managers or similar titles.

      Author

      As you may have guessed, authors can write and publish their own posts and pages. They can also delete their own posts.  However, they cannot publish, edit, or delete anyone else’s posts. Additionally, authors cannot add or delete users, install or activate plugins, or manage themes:

      WordPress Dashboard

      Unlike Contributors, Authors have access to the WordPress Media Library. While they can edit reader comments, they can only do so on their own posts.

      Contributor

      WordPress Contributors can write and submit their own posts for review by an Administrator or Editor. Once a post is published, they cannot edit it. Furthermore, contributors cannot add or delete users, install or activate plugins, or manage themes.

      Contributors are usually roles assigned to freelance writers or guest bloggers. This role is also commonly used for new hires whose content needs editing or reviewing before it can be published on the site.

      Once submitted for review, only the Editor or Administrator can publish their posts. Contributors cannot access the Media Library.

      Subscriber

      Subscribers can manage their own profiles and read posts and pages on a WordPress site. They cannot write or publish their own posts or pages, nor can they add or delete users, install or activate plugins, or manage themes:

      WordPress User Profile Personal Options screen

      Subscribers have the fewest permissions and capabilities of all the WordPress roles. It is the default user role set for new registrations.

      There are a few additional user role options available on some WordPress sites. For example, if you’re running a WooCommerce site, Shop Managers have similar capabilities to Administrators, but with some added features specifically for managing WooCommerce stores. For instance, they can add and delete products, manage orders, and more.

      How to Manage User Roles in WordPress 

      Now that you have a better sense of what each user role can do, let’s get into how to manage them. Below, you’ll find instructions for how to add, delete, and update users and user roles in WordPress.

      1. Creating and Deleting Users in WordPress

      Before you assign a user role in WordPress, you first need to have a user to attach it to. To add a new user in WordPress, you can navigate to Users > Add New, then fill in the information. This will include details such as username, email, and password:

      WordPress add new User

      Note that, by default, the Role is automatically set to Subscriber. When you’re done, you can click on the Add New User button at the bottom of the screen.

      Alternatively, you can create a new user through your database. To do this, you can navigate to phpMyAdmin from your cPanel dashboard (or whichever system your host uses), then select your WordPress database.

      Next, locate the wp_users table (name may vary depending on your database prefix):

      phpMyAdmin user database

      Once you click on the users table, you can select the Insert tab:

      phpMyAdmin user database

      On this screen, you can enter the following credentials:

      • user_login: The username you want to assign the user.
      • user_pass: The password for the user’s account; you can select MD5 in the Function drop-down.
      • user_email: The email address you want to use.
      • user_registered: The date and time for when the user will be registered.
      • user_status: You can set this value to “0”.

      When you’re done filling out the details, you can click on the Go button at the bottom of the screen. Next, navigate back to your WordPress database, then select the wp_usermeta table, followed by the Insert tab:

      phpMyAdmin user database

      You can insert the following details in the form:

      • unmeta_id: This is autogenerated, so you can leave it blank.
      • User_id: The id of the user you created.
      • Meta_key: You can set this as “wp_capabilities”.
      • meta_value: Add this as “a:1:{s:13:”administrator”;b:1;}”

      Finally, you can add another row. Then, input the following information:

      • Unmeta_id: You can leave this blank.
      • User_id: The id of the user you created.
      • Meta_key: You can make this “wp_user_level”.
      • Meta_value: You can put this as “10”.

      When you’re finished, you can click on the Go button to save your changes.

      To find a full list of your users, you can go to Users > All Users from your admin interface:

      WordPress Users screen

      To delete a user from your WordPress dashboard, you can hover your mouse over the name of the user, then click on the Delete link. That’s it!

      You can delete a user from your WordPress database as well. To do so, log into phpMyAdmin, then navigate to the wp_users table:

      phpMyAdmin user database

      Next to each user, you’ll find an Edit, Copy, and Delete option. Simply select Delete to remove the user.

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      2. Adding a User Role 

      There are a few ways to create a new user role in WordPress. The easiest way is to go through the admin interface. As you may have noticed in the last section, you can assign a user role at the time of creating a new user.

      To assign or update a role to an existing user, you can navigate to User from your WordPress dashboard, then select the Edit link under the user name:

      WordPress User Editor

      At the bottom of the screen, you can select an option from the Role drop-down menu:

      WordPress select User Role Administrator

      When you’re done, you can simply select the Add New User or Update User button at the bottom of the screen.

      Another way you can add a new user role in WordPress is by manually editing your code. For instance, you can add a custom user role, such as Moderator, with the add_role() function.

      To do so, you can add the following code to your theme’s functions.php file:

      add_role( 'new_user_role', __( 'Moderator' ), array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true ) );

      When you’re done, be sure to update the file to save your changes. It’s as simple as that!

      3. Deleting a User Role in WordPress

      If you want to delete a user role in WordPress so that it is no longer an option, you can do so by editing your theme’s files. Keep in mind that modifying theme files can be risky, so it’s best to create a backup of your site before you continue on.

      To get started, go to Appearance > Theme File Editor in your WordPress dashboard. Next, locate and open the Theme Functions file:

      WordPress Theme Editor

      In this file, you can add one (or all) of the following code snippets, depending on which user role(s) you want to remove:

      remove_role( 'subscriber' );
      remove_role( 'editor' );
      remove_role( 'contributor' );
      remove_role( 'author' );

      When you’re done, select the Update File to save your changes.

      4. Updating Existing User Roles and Permissions

      If you want to update an existing user’s permissions, you can select the Edit link from the User list. You can then scroll to the bottom of the screen and modify the role by selecting a new one from the User Role drop-down menu. Remember to save your changes.

      Another option is to use a plugin, such as User Role Editor:

      WordPress User Role editor plugin

      This free version of this tool lets you easily change user roles and capabilities. Once installed and activated on your site, you can browse to Users > User Role Editor:

      WordPress User Role Editor

      Next, you can select the checkboxes of the capabilities you want to allow the selected role to have. When you’re done, click on the Update button at the bottom of the screen to save your changes.

      The plugin also lets you add new roles or delete ones that you aren’t using. It even lets you assign capabilities on a per-user basis.

      Tips for Picking the Right User Roles and Permissions

      As a general rule of thumb, it’s a smart idea to set the user role as low as possible. In other words, you want to give users as few permissions as possible that won’t interfere with or impact their ability to do their assigned tasks.

      Selecting the roles for your users should be based on the level of access that’s necessary.There are also specific roles for certain use cases.

      For example, if you have a full-time writer for your WordPress website, you can assign them the Author role. They’ll be able to write, draft, and publish posts on your site, as well as access the Media Library. However, they won’t be able to access, edit, or delete other pages and posts. Therefore, if this is a necessary capability, you may want to assign them the Editor role.

      On the other hand, if you have a freelance writer or a new hire that you don’t want to give publishing privileges to, you can make them a Contributor. This will let them write pages and posts, but they won’t be able to publish them. They can only submit it to the Editor (or Admin) for review.

      Consider assigning the Contributor role to anyone that doesn’t work in-house. We also recommend having as few Administrators as possible. This can help safeguard your site and prevent errors.

      If you have a multi-site installation, it’s a good idea to have one Super Admin. That way, they can handle any security or site issues that arise on any of the sites without interference or confusion from other admins. However, you could assign a single Administrator or Editor for each of the sites within your multisite network.

      Troubleshooting WordPress User Role and Permission Issues

      WordPress user roles and permissions are relatively straightforward and easy to use. However, sometimes issues arise, which can make it difficult for users with certain roles or permissions to carry out their tasks properly.

      One of the most common is being locked out of your WordPress admin and encountering a page with the message “Sorry, you are not allowed to access this page”. This error can be frustrating because it can be challenging to nail down the cause of it.

      However, if you see this message it’s likely because there’s a permission setting that is preventing you from accessing a certain area for security purposes. If you’re an Administrator or should have access, there are a few potential solutions you can try out.

      If this issue occurred directly after a WordPress update, restore the previous version of your site. Next, you can try disabling all of your plugins and re-enabling them one-by-one. You can also try activating a default WordPress theme. These steps can help you narrow down the source of the notification.

      Alternatively, you can check to ensure that you have the necessary Administrator privileges. To do this, navigate to phpMyAdmin then to the wp_users table.

      Next, locate your username and make a note of your ID. Browse to the wp_usermeta table and locate your metauser ID:

      phpMyAdmin user database

      Under the Metavalue column, it should read as the following:

      A:1:{s:13:"administrator";s:1:"1";}

      If there is something else in this field, we recommend editing it to replace it with the above. Simply save your changes when you’re done.

      Useful WordPress User Role and Permissions Plugins

      At this point, you likely understand the various settings and options you have for changing user roles and permissions in WordPress. However, to make the process even easier, you might consider using a plugin.

      We already discussed the User Role Editor plugin, but there are a handful of additional options to choose from. Below, we’ll take a look at some of the most popular ones and explain what you can use them for.

      Members

      Members is a plugin that lets you manage the permissions of registered users:

      MemberPress

      It’s beginner-friendly, boasting an intuitive interface that is easy to navigate. You can use it to create new roles and add permissions to each one. You can also clone user roles and customize the permissions for blog content.

      PublishPress Capabilities

      PublishPress Capabilities is another useful tool that can help you gain more control over your user roles:

      PublishPress

      It lets you add new roles, clone existing ones, and add individual permissions for each role. You can also backup, migrate, and restore the permissions. It can be used for single websites or on multisite networks. The plugin also integrates seamlessly with WooCommerce, which is helpful for store and product management.

      WPFront User Role Editor

      WPFront User Role Editor is a popular plugin you can use for managing user roles in WordPress:

      WPFront

      You can use it to create, delete, and modify user permissions. You can add new names for roles and clone existing ones. It also lets you assign multiple roles to users.

      Take Control of User Role Management on Your WordPress Site

      If you’re looking to manage WordPress user roles and permissions, it’s important to understand the different capabilities associated with each role. With this information, you can better manage your site and ensure that users have the appropriate level of access to your content and features.

      Whether you’re managing a simple blog or creating a complex website with multiple authors, user permissions are an important part of WordPress. With the right set of permissions in place, you can ensure that your site remains secure and runs smoothly.

      Are you interested in learning about more ways you can make managing your WordPress site as simple as possible? Check out our Managed WordPress Hosting solutions to learn about DreamPress!

      Do More with DreamPress

      DreamPress’ automatic updates, caching, and strong security defenses take server management off your hands so you can focus on content creation.

      Managed WordPress Hosting - DreamPress



      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