Vue.js Series Tutorial 3:vue

Source: Internet
Author: User
Tags sublime text

Original: Intro-to-vue-3-vue-cli-lifecycle-hooks

Translator: Nzbin

This is the third part of the JavaScript framework vue.js five tutorials. In this section, we will learn vue-cli and also involve the real development process. This series of tutorials is not a complete user manual, but rather a basic knowledge that gives you a quick overview of Vuejs and its uses.

Series Articles:
    1. rendering, directives, events
    2. Components, Props, Slots
    3. Vue-cli (here you are!)
    4. Vuex
    5. Animation
VUE-CLI and build process

If you have not read the previous section on Vue.js components and props, I strongly recommend that you read the previous section before reading this article, and that part of the content is lacking in context.

Vue provides a handy command-line tool that lets you select some build tools to launch your project and also provides a simple startup template. This is a very good tool. Before installing VUE-CLI, you need to check the version of node and upgrade NPM or yarn. The first thing to install is vue-cli (-G = global installation)

$ npm install -g vue-cli

There are a variety of build tools to choose from, but in our example we will use Webpack:

$ vue init webpack <project-name>

You can install all content from the command line into the directory, set the ' Package.json ' file, and then start the local service on the localhost:8080 port with the following command:

$ npm run dev

The program runs successfully! I like this simple setup. You can start the project from the APP file in the '/src/' directory and the ' Hello.vue ' file under '/components/' directory. This is very good because you have seen how to build files and how to import and export files.

Take a look at the file extension '. Vue ' because you haven't used Vue before, so you haven't encountered this kind of file before.

In the '. Vue ' file, you can put any component content. We don't need to reuse the <script type="text/x-template"> package template, and now we're going to create a more semantically-based file with the following logic:

<template>  <div>     <!--Write your HTML with Vue in-and      </div></template> <script>  Export Default {     //Write your Vue component logic here  }</script><style scoped> /  * Write your styles for the component in here */</style>

I have built a Vue snippets repository for Sublime Text, and can quickly generate the above template for the '. Vue ' file (this is vbase the snippet output). This is for atom (it points out that Vue needs a 1+ version, and Vue is now V2), and this is for Vscode.

Here are a few things to note: Like React, you must return a closed tag, where I use a div. I also use elements in SVG <g> . Any label is allowed, but the entire template must be wrapped in a label.

You notice that we're going to use scripting here export default , like the data function or methods we used before, but if we want to use subcomponents in this '. Vue ' file, we need to import them (in detail later).

You will also notice that there is a special attribute value in the style label scoped . This allows us to easily limit the style of this component to this component . We will also use <style> it to create a style for the entire program. I usually create a common style sheet for my application, including common styles like fonts and line-heights, so I'll use Vue-style-loader to import the @import tags into the App.vue file <style> . I also use <style scoped> tags to make special styles for the template, but only valid for the current template! The benefit of VUE-CLI is that you decide how you want to organize your files, and you don't have to add other dependencies or modules to limit the scope of your style.

Previously, we introduced slots, which is suitable for components with slots when we use slots with local style labels in Vue components. This is very useful because you can easily switch components and change styles.

In the development process, using special '. Vue ' files to organize html,styles and JS is very helpful. I like the total separation of the ways that can be clearly seen in every part, and I am not accustomed to this tightly connected way. It can speed up my development, and I find that markup language is semantically.

You may have noticed that the syntax highlighting does not automatically recognize the '. Vue ' file, so I installed this in Sublime Text.

Here is the basic way to import/export a component to a file (in Vue-sublime snippets is VIMPORT:C):

Import New from './components/new.vue ', export default {components  : {    appnew:new  }}

As an example of life, take a look at the last example of the bottle label we used, its components have two separate templates:

App.vue:

<template> <div class= "container" > <main> <component:is= "selected" > <svg class= " Winebottle "aria-labelledby=" title "xmlns=" Http://www.w3.org/2000/svg "viewbox=" 0 155 "> ... </ svg> </component> </main> <aside> 

Black Components:

<template>  <div>    <slot></slot>  </div></template><style Scoped>  . label {    fill:black;  }  . Bottle,. wine-text {    fill:white;  }  . Flor {    fill: #ccc;  }  . bkimg {    filter:url (#inverse)  }</style>

Note that I've set a different style here for the slots in the component, which is a good way to work, but that's just one way. There are many ways to build programs through components,slots and props. The code here also shows only part of the content. I built the warehouse for the sample, built using VUE-CLI. To familiarize yourself with the workflow, I strongly recommend building components using VUE-CLI and passing states through props. This is intuitive and fast as long as the initial setup is complete.

Life cycle Hooks

Before discussing the life cycle hooks, you need to review the virtual DOM I mentioned in the first article. I mentioned that Vue.js has a virtual DOM, but it doesn't explain its purpose.

When you work with a framework like jQuery, you may have heard of DOM and changed content through DOM updates. Finally, we spent a lot of time checking what the DOM was doing and storing the state. Instead, the virtual DOM is an abstract representation of the DOM, a bit like a replica, but in this case it will be the primary replica. In this series of articles, when we use the state in Vue, we create the state and observe the update of the state.

When a Vue instance is updated, Vue will check to see if it differs from the previous one. If there is a difference, Vue will invoke the life cycle method to update the part of the DOM change. This is to improve efficiency, and in this way the DOM only updates the required parts.

Lifecycle hooks provide a number of methods , so you can precisely trigger certain actions at different moments in the component's life cycle. When we instantiate a component, the component is created, and the other is destroyed, such as when we use the V-if/v-else command to switch.

The hooks you can use are: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy , destroyed . If you want to learn more, take a look at the API documentation that describes each approach. The following small example shows some of the working principles (check the console):

Const CHILD = {  Template: ' #childarea ',  beforecreate () {    console.log ("beforecreate!");  },  ...}; New Vue ({  el: ' #app ',  data () {    return {      isshowing:false     }  },  methods: {    Toggleshow () {      this.isshowing =!this.isshowing;    }}  , components  : {    appchild:child  } });
<div v-if= "isshowing" >  <app-child></app-child></div>

Note that we use it here v-if instead of using it v-show because it v-if will actually create or destroy the component, but v-show just toggle the visibility (the component still exists in the DOM). Similarly, <keep-alive></keep-alive> it is not created or destroyed, but is activated or deactivated-because the component still exists, but it is not used.

As the method in the component automatically binds this, the lifecycle hook also automatically binds the instance, so the state and method of the component can be used. Still do not need to view through this the Console.log point! *heartiest eyes* However, you should not use the arrow function in the life cycle method because it binds to the parent class context, not the Vue instance.

In the following example, when a component is initially created, a large number of elements are moved, so I will use the mounted hook function to trigger the corresponding animation for each component. You can click the return button in the lower right corner to see the start animation.

Mounted () {Let    audio = new Audio (' Https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/rain.mp3 '),        tl = new Timelinemax ();    Audio.play ();    Tl.add ("Drops");    Drops in    tl.staggerfromto ("#droplet-groups g path", 0.3, {      drawsvg: "0% -10%"    }, {      drawsvg: "100% 110% ",      Repeat:3,      repeatdelay:1,      ease:Sine.easeIn    }, 0.5," drops "); ...}

In this example I use a lot of the beautiful and complex features that Vue <transition> provides <transition-group> , and I'll cover them in the last part of the series Animation, and why and when.

Vue.js Series Tutorial 3:vue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.