Month: January 2019

Creating a Vue.JS Instance Using its Fundamental Concepts

Vue.js is simple and powerful, and it is easy to learn. Once you understand the basics of the framework, everything will work in just the way you expect. The framework will help you to keep focused on writing the logic of your application instead of remembering a bunch of APIs that are hard to use. This article will help you learn some of the fundamental concepts in Vue.js.

Fundamental concepts

When you start a Vue application, what you need to keep in mind is your application’s logic itself. You don’t need to remember a set of APIs so that you can connect different pieces of your code. Vue.js, which is a progressive framework, provides you with an intuitive way of writing web applications, starting small and growing incrementally into a large-scale application. If you have used other frameworks before, you may wonder why they make things unnecessarily complicated. Now, let’s go through fundamental concepts in Vue.js and create a sample application. You can also access the complete code for this article at https://github.com/PacktPublishing/Building-Applications-with-Spring-5-and-Vue.js-2/tree/master/Chapter02/MessagesApp.

Creating a Vue instance

Creating a Vue instance is the start of every Vue.js application. Typically, a Vue application consists of two types of Vue instance‚ÄĒthe root Vue instance and component instances. You create the root instance with the Vue function, as follows:

The options object here is where you describe your application. Vue.js takes this object and initializes the Vue instance. Let’s create a simple application, called the Messages App and see how to use the options object. This SPA has the following features:

  • Add a message
  • View messages list
  • Delete a message
  • Automatically disable the add feature under certain conditions

We will start by creating the index.html file and, from there; we will build our application incrementally. Let’s have a look at the index.html file:

In line 5, we create a 

 element with an app id in the DOM. And in line 9, we mount our application to this element by using the el property of the options object. el is short for element, and its value can be a CSS selector string, like the one we use here, '#app', or it can be the HTMLElement itself, document.getElementById('app'). In line 8, we assign the Vue instance to the vm variable, which is short for ViewModel.

Now, let’s define our data model of the application. We need an array to hold those added messages and a string to bind to the form’s input which will accept new messages. Here is how the data object appears:

We add the data object using object literals. As you can see, it is quite straightforward. We give them initial values so that you can easily tell that messages is an array and newMessage is a string. Providing initial values for the data object properties is a good practice. It not only helps you understand the data model better, but also makes those properties reactive by default. 

Besides using a plain object as the value of the data property of the options object, you can also use a function that returns a plain object, as in the example:

Using a function is required when you define the data structure for a component because, in that way, Vue.js will always create a fresh data model for the new component. If you use a plain object to define a component’s data model, all of the instances of that component will share the same data object, which is not desired. For our root Vue instance here, we are safe to use a plain object.

For now, we have only defined the data model, and we haven’t told Vue.js what to do with the data object. Let’s add a template for displaying and adding messages. You can add a template in three ways. One is to add an inline template string using the template property of the options object. It is appropriate to adopt this approach when you create a component that doesn’t have a lot of markups.

The second way is to put the template directly inside the mounting point, 

. Vue.js will parse the template inside #app and replace it with HTML generated by Vue.js. The third way is to put the template markup inside a script tag, for example, <script type="x-template" id="tmplApp">, and put '#tmplApp' as the value of the template property of the options object. We will adopt the second approach here just so we can have the template markup close to the final output. Here is how the template appears:

In line 7, we use the Vue built-inv-for directive to render the messages list. The syntax of the v-for directive is alias in source. In our code, message is alias and messages is source. We don’t need to write vm.messages in order to access the messages property. Just use the exact name that you put in the data object. And by adding the v-for directive to the li tag, we create a v-for block inside the li tag, and that’s where thealias message will be available. You can think of the v-for block as being equivalent to the for-loop block in JavaScript.

In line 8, we use Mustache syntax to output the text property and createdAt property of a message object of the messages list. The createdAt property is a Date object that we add when saving a new message. When Vue.js parses the template and interpolates a Mustache tag, for example, {{message.text}}, it creates data binding between the output and the data. It will replace the tag with the actual value and update the output whenever the text property has been changed. The text interpolation also supports JavaScript expression. For example, you can make the text property always in lower case with {{message.text.toLowerCase()}}.

In line 11, we use another built-in directive, v-on, to attach an event listener to the form’s submitevent.prevent is a modifier, telling Vue.js to call event.preventDefault() so that the browser won’t actually submit the form. addMessage is a method that will be invoked when the form’s submit event is triggered. We will create this method shortly. You can use v-on to attach listeners to all of the normal DOM events, for example, click and mouseover. You can also use it to listen to custom events of Vue’s custom components in the same way. We will see how that works shortly.

In line 12, we use the built-inv-model directive to create a two-way binding between the textarea element and newMessage property of the data object. In this way, whenever the value of the textarea element is changed, the newMessage will be updated automatically. And when newMessage is changed, textarea will be updated accordingly. This is such a nice feature that you can get the value of the textarea element without touching it yourself specifically. It works just as you would imagine it should.

In line 14, we add a button with type="submit" to trigger the submit event of the form. Now, let’s create our addMessage method to listen to that event. We can do it by using the methods property of the options object.

Here is how the options object appears with the addMessage method:

The methods property of the options object takes an object, where you put all of your methods. And inside these methods, you have access to the properties of the data object via this, as you can see that we use this.newMessage and this.messages inside the addMessage method to access them. The method syntax we use here is ES6, but you can also use function expression, as follows:

However, you should not use arrow functions syntax to create methods because you will lose access to the Vue instance via this.

Inside the addMessage method, we add the new message to the messages array using the push() method, and then we reset the newMessage property. Accordingly, Vue.js will clear textarea in the UI automatically. This is the magic of two-way binding, which will be revealed soon.

Now, let’s add a way to delete a message from the UI. Here is what we change in the template:

We add a button and use @click, the short-hand of v-on:click, to attach the listener deleteMessage method to the click event. Instead of putting the method’s name here, we use an inline statement to pass the message object to the method. And here are the updated methods of the options object:

We delete the selected message from the messages array using the Array.prototype.splice() method. Vue.js will detect this change and update the DOM automatically. You don’t need to manipulate the DOM at all.

Now, let’s add the ability to automatically disable the add feature. Let’s say we want to disable the Add button when there are 10 messages in the list. To do that, we can use the built-in v-bind directive to bind the Add button’s disabled attribute with the messages.length >= 10 expression. In this way, Vue.js will update the disabled attribute automatically when the length of the messages array changes. Here is the updated template:

What if we want to change the logic so that the Add button is disabled when the length of the textarea input exceeds 50 characters? You will need to change the value of the v-bind directive to newMessage.length > 50. What if we want to disable the button when there are already 10 messages, or the length of newMessage exceeds 50 characters? We can change the directive value to messages.length >= 10 || newMessage.length > 50. It still works. However, as you can see, the code starts to bloat and it would become hard to maintain when you need to add more logic to decide when the Add button should be disabled.

Here, we can use computed properties. As the name suggests, the value of such a property is computed rather than defined as those in the data object. And Vue.js will track the dependencies of a computed property and update the property’s value when the dependencies change. Let’s add the computed property addDisabled to the options object:

As you can see, the addDisabled computed property is defined as a method of the computed object of the options object. Inside the method, you also have access to the Vue instance via this. For the v-bind directive, there is also a shorthand option, which is a colon (:). Let’s update the Add button in the template to the following:

As you can see, our template becomes much easier to follow and maintain since you keep most of the logic in the JavaScript rather than in the HTML template. 

For the v-bind directive, you can use it to bind the HTML element’s built-in attributes, for example, class and style. You can also use it to bind a Vue’s custom component property. We will see how that works shortly.

By now, we have implemented all of the features of the Messages App. Since we didn’t use¬†<script type="module">, you can open¬†index.html¬†directly using Chrome. If you try it now, you will see something strange. Immediately after opening the file, you can see the template markups that we put inside the mounting point,¬†

, which is awkward. The reason that it behaves in this way is that, before the browser loads Vue.js and executes it, it will display the HTML in the manner it is defined until Vue.js takes control of the DOM and removes the template¬†markups¬†from the mounting point and then replaces it with the new dynamically generated DOM. Let’s fix this by adding the v-cloak directive¬†to the mounting point and inserting a CSS rule to hide the template markups. Vue.js will remove the¬†v-clock¬†directive when the generated DOM is ready. The following are the updates to the¬†index.html¬†file:

Besides the [v-cloak] CSS rule, we add a few other rules to style the UI a little bit, even though it is still very primitive with these rules. Now, if you open it again in the browser, there is no flash anymore. 

By now, you’ve learned how to use the data object, the computed object, and the methods object of the options object of a Vue instance. And you can see that, even though the properties of these objects are defined separately, you can access them in the same way, which is via this

Now, let’s open the Console tab of Chrome’s Developer tools. Instead of using the input field in the UI, let’s add a new message from the console by interacting directly with the vm object, which is the root Vue instance that we created and made available in the global scope. As you can see from the following screenshot, it works as you would expect. This is its simplicity and powerfulness:


The Messages App in Chrome

Apart from the datacomputed, and methods properties, the options object has many other properties that you can use to define a Vue instance.

If you found this article interesting, you can explore Building Applications with Spring 5 and Vue.js 2 to Become efficient in both frontend and backend web development with Spring and Vue. With the help of Building Applications with Spring 5 and Vue.js 2 you’ll get to grips with Spring 5 and Vue.js 2 as you learn how to develop a web application.

Creating and Editing Content in Drupal

Drupal sites are all about content. In order for the site to present content to the visitor, it needs to contain content. How does content get into the Drupal site? In this article, you will learn how to work with content, create it and edit it. So, let‚Äôs get started!

Using the WYSIWYG editor

When you send a text message from your phone, you type the text, and that’s pretty much all there is to it in terms of the content’s appearance. You’re limited to choosing whether you want to use capital letters. If you want more control over your message, you can switch to sending an email message, which might enable you to select bold, italic, or underlined text.

If you want to send highly formatted content, text with headings, font changes, text color, bulleted lists, and so forth, you might use word processing software, such as Word, Pages, or LibreOffice. 

This class of software creates what is called rich text, that is, text rich in styling, and the generic term for software capable of creating a document containing rich text is a rich text editor

Drupal 8 includes a rich text editor called CKEditor. It is a highly configurable editor with a composition area, as shown in the following screenshot, that resembles standalone word processors with formatting buttons. This type of editor is referred to as WYSIWYG, which is pronounced as wizzy-wig, which stands for What You See Is What You Get, meaning that the text it displays shows the selected formatting:

Let’s create a piece of content and reproduce what is in the image. Click on Content in the admin menu, then click on the +Add content button. When you are presented with the list of content types, click Article.

The page contains all the fields and settings necessary for creating Article content. Those fields that require an entry have an asterisk following their name, and I will also include an asterisk as we address each of the fields, in turn.

Title*

The Title is a required field for all content because it is used to identify one piece of content as distinct from another, though it does not have to be unique, and so more than one piece of content can have the same title, which quickly becomes confusing. The entry in this field will appear in the summary admin list of content. It is also used as the page title when the content is read on its own page. Therefore, it is best to enter a title that is both meaningful to you and informative to the site visitor. Enter one now. Mine will be A Moment in the Life of My Dog.

Body

You might be wondering why the Body field is not required since the article would be somewhat useless without body text. It is because you might want to create the article as a draft and return later to actually create the body text. This is not possible with the title, because without one, it would be difficult to find the article.

Summary Field

Next to the field name is a link that reads Edit Summary. When creating a content type, the creator decides whether the body text field should accommodate having a separate summary and if so, that link is shown. The summary is used, for example, when providing a list of content for the site visitor, where a short description of the content‚ÄĒa teaser‚ÄĒis provided.

There are two ways to provide the teaser text: via a separate summary or by trimming, that is, excerpting text from the start of the content. I prefer to use the summary because trimmings are based on a set number of characters that is the same for all of the same type of content, such as the first 40 characters, so I have no control over where the excerpt will end… maybe it will end in the middle of a word. With a summary, I can precisely control what will be shown. Even if it is identical to the start of my body text, I am able to ensure that it ends in an appropriate place.

Click on the Edit Summary link. A Summary text box will appear above that for the body. It contains a link to hide the field again. This toggle of Edit summary/Hide summary allows you to remove its distraction until you need to use it. You will notice that the bottom right corner of the text box has a widget that’s meant to resemble page corners that can be grabbed with the mouse and dragged to enlarge or reduce the size of the text box. It also has a note below it letting you know that if you do not enter summary text into the field, Drupal will use a trimmed version of the body text as a summary. Enter some summary text into the field. Mine will read: Sasha makes an exciting discovery.

Body text

In the Body field goes the full text of the article. Depending on the text format selected, various buttons are available from the editor for formatting the text. My text looks as follows:

Today Sasha Gabor discovered donuts! They’re not exactly healthy diet fare for a dog, but she didn’t seem to mind.

Enter some text for your article, and format some of it using the B (bold) or I (italic) buttons. When you have entered it, click the Source button to see what the actual HTML markup looks like. Mine shall look like this:

If you ever need to customize the underlying HTML of the body text, this is where you can do it. Click the Source button again to return to the WYSIWYG mode.

Text format

The Text format dropdown is used for selecting the filter that will be used when entering text. Security is a constant concern on websites that accept entry from users, as some bad actors will attempt to enter markup that can cause havoc. Filtering which type of markup is allowed helps to mitigate the potential for trouble.

These filters can be defined and configured, and the configuration will, for example, identify which HTML tags will be allowed and which processes will be run (such as HTML correction) and in which order. Filters are assigned to user roles, and a user role can have access to more than one filter. The filters that are included with Drupal and their default configurations are as follows:

  • Plain text: No HTML tags will be accepted
  • Restricted HTML: A minimal set of HTML such as italics, bold, and headings are typically used for anonymous users (users who are not logged in)
  • Basic HTML: Similar to Restricted HTML, but usually inclusive of a configuration for WYSISYG toolbar buttons, since the filter is normally used for authenticated (logged in) users who will have access to the editor
  • Full HTML: Allows any valid HTML tag, and should be assigned with care

 This filter will not be included in the dropdown as it is used when no other filters are available.

Tags

The Tags field is used to include terms related to the content. These terms can be used by users to search for content. Multiple terms should be separated by commas. The field is an auto-complete field, meaning that any existing terms matching the characters typed will be offered for you to click rather than typing the entire term. My tags will be Sasha and donuts.

Images

The Image field enables choosing a file from the device you are using and uploading it to be stored and associated with the content. The maximum size of the file is given below the field (typically 2 MB) and so are the file types that will be accepted. I’m going to add an image and enter Sasha and her donut as alt text. Alt text is used to provide information about the image to those users using a screen reader or some other form of access rather than viewing the image.

Publishing the content

The Published checkbox sets the content’s status to be either draft (unchecked) or published (checked). Typically, only editors, admins, and the content’s author will be allowed to view the content when in its draft state. The content will not appear in menus or lists to those roles that don’t have permission to view it. Let’s check the box to publish our content.

Additional settings

That covers the main fields used to create Article content. There are additional configuration options available via the vertical tabs. Let’s take a look at those:

These additional settings are referred to as metadata, which is information used to describe the content that is not actually part of the content.

Revision log message

If the content type that you are working with is set for revisions, you can enter a description of the changes you have made to the content in this box, and that description will be saved and listed when reviewing the available revisions for this content.

Menu Settings

Should you want a menu link for this content, checking this box will open a dialog for providing the following settings:

  • Menu link title: The text that appears as a link
  • Description: The text shown when the mouse hovers over the link
  • Parent item: The menu link under which this one will be indented
  • Weight: A value which determines the position of this menu item in relation to any others (based on their weights) with the same parent

Comment Settings

If your content type is set to allow comments, you can set this particular piece of content to accept comments (open) or not (or no longer) accept comments (closed).

URL Path Settings

When a new piece of content is created, it is assigned a sequential numeric ID known as the node ID or NID. By default, the URL displayed when the content is presented, similar to http://mysite.com/node/123, where 123 is the NID. If you want your content to have a more meaningful URL than node/123, such as sasha-discovers-donuts, that custom URL, known as an alias, can be defined here.

Authoring Information

If you are creating content on behalf of another user, you can begin typing their username in the text box in this tab and choose the name from the presented matches, as well as specify the date that should be considered the content creation date.

Promotion Options

Content can be “promoted” to a higher status for the purposes of including it on the home page or even featuring it there.

  • Promoted to front page: Some sites determine what content is displayed on the front page by selecting only that content that has been promoted.
  • Sticky at top of lists: If the content is Sticky, it will stay on the homepage while other content is replaced with newer content. This is a good way to have a welcome message remain while other content is cycled.

Completing the process

At this point, we are ready to save our new content by clicking on the Save button. After doing so, the content is displayed for you to see. Note the URL that is shown. In my case, it is node/2. I would rather have something more meaningful for the user and for good SEO, so I will click the Edit tab and navigate to the vertical tab for URL PATH SETTINGS. There, I will enter /sasha-discovers-donuts (the initial slash is required) and save the article again. Now, the browser will show my improved URL. I can still use the original URL of node/2. It has not been removed. Create a better URL for your content in the same way.

You will notice that one of the tabs above your article reads Revisions. Click on it. Because the Article content type is configured to create revisions when saved, and we did not override that by unchecking the Create new revision checkbox, the change we made and saved in order to improve our URL resulted in the change being saved as a new version rather than simply overwriting the original one. In this manner, we could create a new revision every time we edit the content. From this Revisions page, we can do the following:

  • View a list of the previous versions
  • View a previous version
  • Delete a previous version
  • Revert to (restore) an earlier version, foregoing the changes made since

If you found this article interesting, you can explore Drupal 8 Quick Start Guide for your step by step guide with easy to follow instructions for navigating Drupal 8. Drupal 8 Quick Start Guide will clear your path from installation to a building usable site in minutes, and to a customized site in one sitting.

Components in Blazor

Blazor is a component-based framework. In that component is defined as a block of the UI, consisting of both HTML and the corresponding business logic. The HTML helps to render the component on the web page, and the logic handles the database operations or the event handling. A Blazor component is lightweight, flexible, and shareable across different projects.

The bottom line is that all UI fragments can be termed components in Blazor.

Creating a component in Blazor

We will now discuss the following two methods for creating components in Blazor:

  • Using a single file
  • Using a code-behind file

Let’s examine both of them in detail in this section.

Using a single file

We will use a single file with the .cshtml extension to create our component. To create a component file, right-click on the Pages folder of your BlazorDemo project and select New File. Type in the filename as CompDemo.cshtml and press Enter to create the file.

Put the following lines of code inside this file:

Both the HTML and the @functions section are defined in only one file, that is, CompDemo.cshtml. Here, we have defined a PageTitleproperty to set the title on the page. On execution, this page will show a heading and a sample message, as defined in this property. But before running this application, we need to add the navigation link to this page to the \Shared\NavMenu.cshtml file. Open the \Shared\NavMenu.cshtml file and add the following code to it:

This will add a Comp Demo navigation menu item, which will redirect to the CompDemo.cshtml page when clicked.

Type the dotnet run command into the VS Code console and press Enter. Open the URL in the browser, and you should see a page similar to one shown in the following screenshot:

You can observe that we have a Comp Demo link in the navigation menu on the left. Click on it to navigate to the CompDemo.cshtml component. It should open a page like the one shown in the following screenshot:

You can observe that the route URL of the page has /singlepagecomp attached to it, and that the message is being displayed on the page as we defined it in our component.

Using a code-behind file

In this method, we will be using two files to create our component‚ÄĒone file to hold the HTML part of the component and another to hold the logic part of the component.

To add the files, we will follow the same process that we employed earlier. Right-click on the Pages folder and select New File. Name the file CodeBehindComp.cshtml and press Enter to create the file. This file will contain the HTML section of our component. Similarly, add one more file, CodeBehindComp.cshtml.cs, to the Pages folder. This file will contain our logic section, which will define the members of the component class.

Open CodeBehindComp.cshtml.cs and put the following code into it:

Here, we have defined a CodeBehindCompModel class that contains a PageTitle string property, which sets the title of the component once it is rendered as a web page in the browser.

Note that the Blazor compiler generates classes for all of the view pages with the same name as the page name; hence, we have suffixed the class name with the word “model” to distinguish it from the page name. If we use the same class name as page name (CodeBehindComp, in this case), then it will result in a compile time error.

Open CodeBehindComp.cshtml and put the following code into it:

This page will inherit the class defined in our code-behind page by using the @inherits directive. This allows us to use all of the properties and methods defined in the class from this page.

Add the navigation link for this page, as defined in the following snippet, inside the \Shared\NavMenu.cshtml file:

Execute the application by running the dotnet run command, and click on the Code Behind Comp link in the navigation menu on the left. You should see a page similar to the one shown in the following screenshot:

Here, the title of the page is set to Component Demo because of the PageTitle variable defined in the code-behind file, whereas the messages is displayed using the HTML defined in the .cshtml file.

Using a component within another component

The Blazor framework also allows us to use a component within another component. This will work like a parent-child relationship, where the parent component can refer to the child component.

We will demonstrate this concept with the help of an example.

Create two files in the Pages folder, and name them ParentComp.cshtml and ChildComp.cshtml.

Open the ChildComp.cshtml page and put the following code into it:

Here, we first defined some dummy messages to be displayed on the page. There is no route defined for this component, as it will act as a child component and will be referred to by another component. The parent component will pass the content to the child component so that it can be rendered in a <div> tag. We will use a RenderFragment property, ChildContent, to hold the message supplied by the parent component. ChildContent is a component parameter decorated by the [Parameter] attribute. RenderFragment is defined in the application metadata, and represents a segment of the UI content, implemented as a delegate that writes the content to an instance of Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder.

The component parameter must fulfill the following two criteria:

  • It must be a non-public property
  • The component parameter that will receive the RenderFragment content must be named ChildContent

Open ParentComp.cshtml and enter the following code:

We defined the route of this application at the top of the preceding snippet as /ParentComponent. To refer to the child component, we use a tag with the same name as the file name of the child component, which is <ChildComp>in this case. The RenderFragment parameter is provided between the tags of the child component. In this case, we provide a string message that will be rendered by the child component.

Before executing the code, we need to add the following navigation link of the parent component to the \Shared\NavMenu.cshtml file:

Run the application and click on the Parent-Child link in the navigation menu. You should see a page similar to the following screenshot:

You can see the content of the parent component, along with that of the child component, displayed on the page.

If you found this article interesting, you can explore Blazor Quick Start Guide to work with the fundamentals of Blazor to create rich and interactive web application. Blazor Quick Start Guide introduces you to the core concepts of Blazor, and how to apply these to a real-world web app with the help of Entity Framework Core and SQL Server.