[SPA development with Rails x Vue] Learn the basics of Vue.js (Overview of vue.js, template syntax)

background

I aim to change jobs from inexperienced to engineer. I decided to study SPA development using Rails API and vue.js to create a good portfolio.

The current level of knowledge is that you can easily develop applications using Ruby on rails, version control using git, and deploy using heroku. I hope it will be of some help to those who are thinking of trying vue.js in their own memorandum and at the same level.

Goal of this article

Understand the basics of vue and the basic grammar of vue

【reference】 This article is from udemy's course "Super Vue.js 2 Complete Pack-No more buying other materials! (Including Vue Router and Vuex) ”is the output of what you learned. Therefore, the code etc. are based on the content of the course.

【Related article】 [SPA development with Rails x Vue] Learn the basics of Vue.js (Overview of vue.js, template syntax) [SPA development with Rails x Vue] Learn the basics of Vue.js (vue instance component VueCLI) [SPA development with Rails x Vue] Learn the basics of Vue.js (custom directive transitions, etc.) [SPA development with Rails x Vue] Learn about Vue Router / Vuex

table of contents

  1. About javascript trends
  2. About Vue.js
  3. About SPA
  4. About the basic grammar of Vue.js

Let's go fast!

1. About javascript trends

javascript is implemented in most web applications and is easy to write Nowadays, the three major frameworks vue, react, and angular are attracting attention. If you look at the trends, you can see that jQuery is on the decline, but the three major frameworks are on the rise.

【reference】 See from the trend which of Vue.js vs React vs Angular to choose What is jQuery? Why should I not use it (or should not use it)?

This time, I would like to select vue, which has a low learning cost and can be easily introduced even in small-scale development.


2. About Vue.js

Along with react, vue.js is used by many companies in Japan. There are four main reasons why vue.js is adopted by many companies.

I. Easy to install and flexible

For example, in rails 6.0, you can use vue.js by installing webpacker for vue.js and writing only one line. In other words, it is possible to partially use vue.js for the rails application, and you can mainly develop vue.js with api development.

Ii. Low learning cost

The feature of vue.js is that it is easy for beginners to learn as long as they understand HTML, CSS, and javascript. Also, since the vue.js formula supports Japanese, if you have a problem, you can usually solve it by looking at the formula.

Iii. Efficient development

vue.js makes it easy to assemble applications in units called components. Components are like parts that make up the UI, and by making them common, they can be used over and over again.

Iv. Virtual DOM, types crpit, etc. can be used

The javascript framework is becoming standard to use technologies such as virtual DOM and Typescript. Since vue.js also supports virtual DOM and typescript, it can be implemented faster and more extensible.

【reference】 (vue.js official) Introduction -What is vue.js? (vue.js official) Comparison with other frameworks

3. About SPA

SPA is an abbreviation of "Single Page Application", and as the name suggests, it is an application that switches contents on one page. Specific examples include slack and google map. Both can get new information without transitioning pages (leaving a single page). SPA is a mechanism that has been attracting attention in recent years because the page transition time is short and the UX is increased.

You can easily build a SPA using vue.js.

【reference】 Basics of SPA (Single Page Application)


4. About the basic grammar of Vue.js

Now let's check the basic grammar of vue.js.

■ About files

Installation of vue.js is divided into three types: "CDN", "npm", and "vuecli". "CDN" is the method described in the body tag of html, "npm" is the method of using the package manager of node.js, and "vuecli" is the method of using the vue command in the terminal. This time we will use "CDN". Create index.html appropriately and describe as follows.

index.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <div id="app">
  </div>
  <script>
    new Vue({
      el: "#app",
    })
  </script>
</body>
</html>

--The inside of the head tag is the same as the normal html description. --The description on the first line of the body tag calls vue on the CDN. With this alone, you can use vue.js. Notice that the body tag contains this call. --For the div tag, the id is specified by app. This is to determine the scope of vue.js that you will specify later. --The script tag "new Vue" is creating a vue instance. Simply put, it's a declaration that uses vue.js. ――The part of "el:" #app "is called el property, and it describes where to apply vue.js. Since the id called app is specified here, is specified in the div tag earlier.

The above is the preparation of the file to use vue.js. I will explain the detailed grammar from the next, but I will omit everything in the head tag, body tag, and CDN call part.

■ Call the value of vue.js

index.html


<div id="app">
 <p>{{message}}</p>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
       message: "HelloWorld",
    }
  })
</script>

--You can set the key and value by declaring "data:" in the vue instance. --The value set in "data:" can be called in double brackets like {{key}} in the template. --It can be treated like the syntax of javascrpt in double brackets. In the above, num is plus 3.


■ Call a method

index.html


<div id="app">
 <p>{{greeting()}}</p>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
       message: "HelloWorld",
    },
    methods: {
      greeting: function(){
         return this.message;
      }
    }
  })
</script>

--You can set methods by declaring "methods" in the same way as "data:". --"Greeting" is the method name, followed by the function written in javascript. --Add this when referencing a key or value in the same instance, such as "this.message". --When calling a method in a template, don't forget the "()" after the method name.

■v-bind

index.html


<div id="app">
 <a v-bind:href="url"> qiita <a>
</div>

<script>
  new Vue({
    el: "#app",
    data: {
       url: "https://qiita.com/"
    }
  })
</script>

--Things that start with "v-" are called directives and refer to the vue.js attributes that can be used in the template. --"V-bind" can be specified for HTML attributes and vue.js can be called. In this case, the href attribute is specified in "v-bind: href". And "= url" calls the url described in vue.js --Since "v-bind" is often used, it can be abbreviated as ": href". --If you wrote the object in vue.js, you can also call the object.

■v-on

index.html


<div id="app">
 <p>num<p>
  <button v-on:click="countUp"> COUNT UP </button>
</div>

<script>
new Vue({
  el: "#app",
    data: {
       num: 0
    },
    methods: {
      countUp: function() {
          this.num += 1
      }
    }
  })
</script>

--"V-on" specifies a specific event. Since this time it is click, the time when the click occurs is specified. --The method is called with "countUp". --Since v-on is also often used, it can be abbreviated as "@click".

■ Event object / argument

index.html


<div id="app">
 <p>num<p>
  <button v-on:click="countUp(4)"> COUNT UP </button>
 <p v-on:mousemove="change($event, 3)"> Change 
  <span v-on:mousemove.stop> No Change </span> <p>
 <P> {{x}}: {{y}}
</div>

<script>
  new Vue({
    el: "#app",
    data: {
       num: 0
    },
    methods: {
      countUp: function(times) {
          this.num += 1 * times
       },
      change: function(event, square) {
          this.x = event.clientX * square
          this.y = event.clientY * square
    }
  })
</script>

--It is also possible to take arguments like normal javascript. --You can get the event object with "function (event)". Specifically, this time we are getting information on the X-axis and Y-axis when mouse moving. --Use "$ event" if you want to specify an event object and use more arguments. --If you use ".stop", it will not respond to the specified event. In this case, even if you hover the mouse over "No Change", it will not respond. There is also a modifier called ".prevent" that interrupts event processing.

■v-model

index.html


<div id="app">
 <input type="text" v-model="message">
 <p>{{message}} <p>
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        message: "hello!"
      }
   })
</script>

--"V-model" is a directive that enables bidirectional binding. Two-way binding is simply joining data. In this example, the characters entered in the input tag form and the contents of the p tag are combined, and the contents entered in the input are immediately reflected in the p tag and output.

■computed

index.html


<div id="app">
 <button @click="count += 1"> COUNT UP </button>
 <p>{{lessThanThree}} <p>
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        count: 0
      },
    computed: {
      lessThanThree: function() {
        return this.count >= 3 ? "3 or more" : "Less than 3"
     }
  })
</script>

--"Computed" is a dynamic property. --While "data" specifies properties related to initial values, "computed" specifies properties that change. Therefore, the inside of "computed" is defined by a function. ――The difference between "computed" and "method" is how to read the file. While "computed" updates only the part specified by the function, "method" updates everything except the relevant part. Therefore, "computed" loads faster.

■watcher

index.html


<div id="app">
 <button @click="count += 1"> COUNT UP </button>
 <p>{{lessThanThree}} <p>
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        count: 0
      },
    computed: {
      lessThanThree: function() {
        return this.count >= 3 ? "3 or more" : "Less than 3"
    },
    watch: {
       count: function() {
         var vm = this;
         setTimeout(function(){
           vm.count = 0
         }, 3000)
       }
    }
  })
</script>

―― “Watch” is an asynchronous process. --Basically, you can use "computed", but in this case, for example, if there is no "{{lessThanThree}}" part in the template, an error will occur if it is "computed". This is because computed is a synchronous process, and there must be a place to synchronize. --The inside of "watch" is written using a function, but since "this" cannot be used in the description of asynchronous processing, it is necessary to assign it to a variable.

■ Class-style binding

index.html


<div id="app">
 <p :class="classObject"> Hello </p>
 <button @click="Active = !Active"> Change </button>
  <h1 :style="styleObject"> Hello </h1>
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        styleobject: {
           color: 'red',
           'background-color': 'blue'
        },
        Active: true
      },
      computed: {
        classObject: function(){
          return{
            red: this.Active, 
            'bg-blue': !this.Active}
        }
      }
  })
</script>

--When binding a class or style, you can specify it as an object or as an array as described above. --You can switch styles dynamically by setting "Active: true".

■v-if

index.html


<div id="app">
 <template v-if="ok">
   <p>Hello</p>
   <p>Goodbye</p>
 </template>
 <template v-else-if="maybe">
   <p>good morning</p>
   <p>good night</p>
 </template>
 <p v-else="ok"> sorry </p> 
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        ok: true,
        maybe: true
      }
  })
</script>

―― “Template” has almost the same role as div, but the feature is that “template” is not displayed when you actually display it in a browser. --"V-if", "v-else-if", and "v-else" are conditional branches. It is almost the same as ruby. This time, true and false are specified in the data of vue.js. --As a side note, there is a directive called "v-show" that plays a similar role. When "v-if" is false, the description disappears completely from the DOM, while "v-show" erases the description by setting css to "display: none". "V-if" is easier to use, but "v-show" is faster to load.

■v-for

index.html


<div id="app">
 <ul>
  <div v-for="fruit in fruits" :key="fruit">
    <p>{{fruit}}</p>
  <hr>
  </div>
 </ul>
</div>

<script>
  new Vue({
    el: "#app",
      data: {
        fruits: ['Apple', 'Peaches', 'Grape']
      }
  })
</script>

--"V-for" is an iterative process. In ruby, it is each method. ―― “Fruits in fruits” means to take out each fruit from the fruits array, assign it to fruit, and execute the process. --": key" specifies the key as its name suggests. When using "v-for", basically set the key as well. --You can also take a second argument like "(fruit, key) in fruits". --You can use "v-for" not only for arrays but also for objects. ――It is also possible to change "in" of "fruit in fruits" to "of". --You can also enter an integer value such as "n in 5" (* It is a method of "5.times ~" in ruby)


This concludes the basics of template syntax. Next time I will write an article about vue instants and components. Also, although the display on the browser is omitted, it is recommended to check it as appropriate.
# Summary / impression I thought that vue.js should be intuitive, but I felt that it was very important to understand plain javascript. So I would like to review javascript again, especially how to use this and how to use functions.

reference

【udemy】 "Super Vue.js 2 Complete Pack-No more buying other materials! (Including Vue Router and Vuex) ” → Recommended! This article is also based on what I learned in this course. It explains carefully from the basics, and since it touches on SPA development, this alone can cover the basics of vue.

"Vue JS introductory definitive edition! Web development without jQuery --- Systematically learn from introduction to application development with videos ” → I thought it would be good to explain the grammar in detail.

Recommended Posts

[SPA development with Rails x Vue] Learn the basics of Vue.js (Overview of vue.js, template syntax)
Roughly the flow of web application development with Rails.
About the basics of Android development
[Challenge CircleCI from 0] Learn the basics of CircleCI
part of the syntax of ruby ​​on rails
The story of making an electronic New Year's card app with Vue.js + Rails
[Rough explanation] How to separate the operation of the production environment and the development environment with Rails
Docker the development environment of Ruby on Rails project
Read the Rails Guide (Overview of Action Controller) again
Challenge the settings for developing with vue.js on Rails 6