[] Vue.js from entry to the master tutorial

Here Insert Picture Description

  • VUE (pronunciation / vjuː /, similar to the view) is a progressive frame for constructing user interfaces. The other frame difference is large, Vue is designed to be applied from the bottom up layer by layer. Vue core library focus only on the view layer, is not only easy to use but also easy to integrate third-party libraries or existing project. On the other hand, when used in conjunction with a modern tool chain and various support libraries, Vue also fully capable of providing drive for complex one-page application.

002 to achieve the first VueJS application .html

  • Download VUE: https://unpkg.com/vue/dist/vue.js
  • The vue.js copied to any directory (working directory)
  • Create a new file in the same directory, enter the following code:
     <script src="vue.js"></script>
     <div id="app">
         <p>{{title}}</p>
     </div>
     
     <script>
         new Vue({
             el:"#app",
             data:{
                 title: "Hello World!"
             }
         });
     </script>
    

This application .html extension 003 VueJS

  • code show as below:
    <script src="vue.js"></script>
    <div id="app">
        <input type="text" v-on:input="changeTitle">
        <p>{{title}}</p>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                title: "Hello World!"
            },
            methods: {
                changeTitle:function (event) {
                    this.title = event.target.value;
                }
            }
        });
    </script>
    
  • Try it, you enter each character will be cloned, a very interesting program!

009-VueJS template syntax and examples .html

  • In the above example, by creating this new Vue instance, attention, although not put it into a variable within, or Vue instance is created.
  • By creating this Vue instance, just like our HTML code to establish a link, Vue based on the above HTML code to create a template, pay special attention to that, Vue when in motion, do not
    directly use the HTML code we write . Pages inside the actual operation of these commands do not we write (the final page and you can not see things like braces),
  • Vue according to the template stored in the HTML code created in-house, and then use this template to create a true rendering of HTML DOM code we write HTML code is not the last in a
    run inside the browser that a middle layer of the HTML instances Vue code into the template, and then render the template (such as the curly braces {{title}}}, etc.), and eventually by its output the rendered HTML code
  • Vue example data stored in the attribute data, such as the above title, they can be modified directly in the attribute data, you can also function to call methods in the generated content. E.g:
    <script src="vue.js"></script>
    <div id="app">
        <!-- 注意此处并没有调用Vue模板,而是调用了一个函数 -->
        <p>{{sayHello()}}</p>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                title: "Hello World!"
            },
            methods: {
                //此处sayHello是一个方法(函数),但它返回的内容被传送到模版里去了
                sayHello:function (event) {
                    return 'Hello!';
                }
            }
        });
    </script>
    

010 instances where the data access Vue .html

  • Anywhere in vue instance, you can use this to access all the properties and methods
    <script src="vue.js"></script>
    <div id="app">
        <p>{{sayHello()}}</p>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                title: "Hello World!"
            },
            methods: {
                
                sayHello:function (event) {
                //注意此处,return的是Hello World!
                //原生的JS是不允许这么调用的,Vue在中间层做了调剂
                    return this.title; 
                }
            }
        });
    </script>
    

011- attribute binding .html

  •   <script src="vue.js"></script>
      <div id="app">
          <!-- 注意:此处不能用<a href="{{link}}"> 这种形式来传递超链接值,只能用v-bind绑定并设置href的值 -->
          <p>{{sayHello()}} - <a v-bind:href="link">Baidu</a> </p>
      </div>
      <script>
          new Vue({
              el: "#app",
              data: {
                  title: "Hello World!",
                  link:"http://baidu.com"
              },
              methods: {
      
                  sayHello:function () {
                      return this.title;
                  }
              }
          });
      </script>
    

012- understand and use instructions

  • Instruction is that you put the code some indication of
  • Such as the above v-bind, and it will be something our data (href value) binding, generally speaking directly in the HTML if needed
    when the display content, we use curly braces to solve, but does not apply when the braces , it is necessary to use the instruction.
  • format:
    • + + Colon command parameters, such as v-bind: href = "link"
    • link is the content you want to bind from Vue instance, can be a property or function
    • Generally you can not pass data to dynamic HTML attribute, with these Vue instructions on it

013 prohibit the use of v-once secondary rendering .html

  • Enter the following code:
<script src="vue.js"></script>
<div id="app">
    <!-- 注意此处的v-once -->
    <h1 v-once>{{title}}</h1>
    <p>{{sayHello()}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            title: "Hello World!",
        },
        methods: {

            sayHello:function () {
                this.title = 'Hello';
                return this.title;
            }
        }
    });
</script>
  • Run the above code, we want the original intent of a Hello World! And Hello, but two elements are rendered Hello, how do?
    With v-once, that is where the first element h1 plus a v-once, it means that the element will only be rendered once, then can not be
    changed.

014 How to output-based HTML.html

  • Enter the following code:
<script src="vue.js"></script>
<div id="app">
    <!-- 注意此处的v-once -->
    <h1 v-once>{{title}}</h1>
    <p>{{sayHello()}}</p>
    <!-- 注意:v-html指令让finishedLink以渲染后的HTML格式输出,而不是纯文本
    如果以花括号{{finishedLink}} 来表示的话,将会是一个HTML形式的纯文本。
    -->
    <p v-html = "finishedLink" ></p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            title: "Hello World!",
            finishedLink:'<a href="http://baidu.com">Baidu.com</a>',
        },
        methods: {

            sayHello:function () {
                this.title = 'Hello';
                return this.title;
            }
        }
    });
</script>
  • The code above will not output a hyperlink Baidu.com, but together with all the HTML code output.
  • The advantage is, HTML elements will not be parsed and rendered, but is output as plain text, to avoid cross-site attacks.
  • However, if under certain circumstances you really want to render HTML code output, such as where you really want to see a
    hyperlink Baidu, you should use the v-html instructions. V-html can embed in the desired element. Please use caution this
    directive, it will expose you to XSS attacks, such as content here may be submitted by the user, you can not control users to upload
    any content to determine if the content security, or by your own code synthesis , it is safe to use v-html

1 015 jobs

  • 015 jobs 1-1.html
  • Output your name and age, both of which are stored as an attribute in the data, output in the P tag inside
<script src="vue.js"></script>
<div id="app">
    <p>I am {{name}}</h1>
    <p>I am {{age}} years old.</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            name: "Rockage",
            age: "40",
        }
    });
</script>
  • 015 jobs 1-2.html
  • 在插值语法中,即在大括号中, 使用JavaScript表达式,输出的年龄乘以3
<script src="vue.js"></script>
<div id="app">
    <p>I am {{name}}</p>
    <p>I am {{age * 3}} years old.</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            name: "Rockage",
            age: "40",
        }
    });
</script>
  • 015-作业1-3.html
  • 调用函数,输出这个函数的返回值,函数返回一个0到1之间的随机数
<script src="vue.js"></script>
<div id="app">
    <p>The Random Number is : {{sayRnd()}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        methods: {
            sayRnd: function () {
                // random_number = Math.random(); // 产生一个0到1的随机数
                // random_number = random_number.toFixed(2) //保留两位小数
                // 产生一个1到100的随机数
                random_number = Math.floor(Math.random() * (100 - 1 + 1)) + 1
                return random_number;
            }
        }
    });
</script>
  • 015-作业1-4.html
  • 使用baidu, 让一个img标签显示搜索到的图片
  • 和超链接的href属性一样,也不允许直接将URL强填进img的src里面,应该把URL存在data里面,绑定到img标签的src属性
<script src="vue.js" xmlns:v-bind="http://www.w3.org/1999/xhtml"></script>
<div id="app">
    <img  v-bind:src = "url">
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            url: "http://img.mp.itc.cn/upload/20170217/1f650c2645c541ad8cc70842d7d0bbe5_th.jpeg"
        }
    });
</script>
  • 015-作业1-5.html
  • 用名字预先填充一个TextBox,让它默认显示你的名字
<script src="vue.js" xmlns:v-bind="http://www.w3.org/1999/xhtml"></script>
<div id="app">
    Name <input type = "text" v-bind:value = "default_name" />
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            default_name: "Hua Yang"
        }
    });
</script>

017-监听事件.html

  • 通过指令v-on监听来自模版的事件
  • v-on 可以监听任何由这个按钮产生的DOM事件
  • 格式: v-on:事件名称 = “事件函数名”,如v-on:click = “increase”
<script src="vue.js"></script>
<div id="app">
    <button v-on:click="increase">Click Me</button>
    <p>{{ counter}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter: 0,
            x: 0,
            y: 0
        },
        methods: {
            increase: function () {
                this.counter++;
            }
        },

    });
</script>

018-从事件对象里获取事件数据.html

  • 用v-on来获取事件数据
  • 这个例子很好地说明了如何通过Vue传递事件对象
<script src="vue.js"></script>
<div id="app">
   <p v-on:mousemove="updateCoordinates">Coordonates : {{x}}/{{y}}</p>
</div>
<script>
   new Vue({
       el: "#app",
       data: {
           counter: 0,
           x: 0,
           y: 0
       },
       methods: {
           updateCoordinates: function (event) {
               this.x = event.clientX;
               this.y = event.clientY;
           }
       },

   });
</script>

019-传递你自己的事件参数.html

  • 给组件传递自定义参数,方法很简单,在调用函数或者说
    设置引用时传入参数即可。
  • 加入不仅要传递自定义参数,还要传递DOM生成的事件对象给方法,
    也很简单,只需要再加一个参数,但这个参数的命名需为
    $event,vue会自动捕捉这个默认的事件参数,并复制给一个可以在
    函数中使用的变量
  • 本例中不对$event做详解,下面的例子会提到它
<script src="vue.js"></script>
<div id="app">
   <!--
   请注意, 调用increase时增加了两个参数
   -->
   <button v-on:click="increase(2,$event)">Click Me</button>
   <p>{{ counter}}</p>
</div>
<script>
   new Vue({
       el: "#app",
       data: {
           counter: 0,
           x: 0,
           y: 0
       },
       methods: {
           // increase 函数用step和event接收参数
           increase: function (step,event) {
               this.counter += step;
           }
       },

   });
</script>

020-用事件修饰符来修改事件.html

  • 现在我们用#11(鼠标悬浮显示XY坐标)那个为例
  • 我想设置一个区域,姑且称为DEAD SPOT, 鼠标进入这个
    区域XY停止更新。
  • 常规方法是让这个SPAN也绑定一个mousemove事件,然后调用
    一个事件函数,事件函数不做任何处理。
HTML中:
<span v-on:mousemove = "dummy">DEAD SPOT</span>

JS中:
dummy: function(){
event.stopPropagation();
}
  • 以上代码确保事件不会传播给绑定有这个属性的SPAN上。
  • Of course, there's an easier way is to use the event modifier.
  • Stop using the modifier to achieve this objective
<script src="vue.js"></script>
<div id="app">
    <p v-on:mousemove="updateCoordinates">Coordonates : {{x}}/{{y}}
        <!-- 请注意下面这个SPAN绑定的事件mousemove
        采用了.stop修饰符,表示此元素的mousemove事件不做任何处理
        -->
        - <span v-on:mousemove.stop = "">DEAD SPOT</span>
    </p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter: 0,
            x: 0,
            y: 0
        },
        methods: {
            updateCoordinates: function (event) {
                this.x = event.clientX;
                this.y = event.clientY;
            }
        },

    });
</script>

021- monitor keyboard events .html

  • This example is very simple, to monitor key events in the input box
  • Once typing the Enter key, Alert pop-up window.
<script src="vue.js"></script>
<div id="app">
    <input type = "text" v-on:keyup.enter="alertMe" />
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter: 0,
            x: 0,
            y: 0
        },
        methods: {
            alertMe: function () {
                alert("Alert!");
            }
        },

    });
</script>

2 022 jobs issue: Event .html

  • Job 2-1: Press the button to pop up a warning box.
<script src="vue.js"></script>
<div id="app">

  <button v-on:click="alertMe">Show Alert</button>

</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter: 0,
            x: 0,
            y: 0
        },
        methods: {
            alertMe: function () {
                alert("You Clicked me!");
            }
        },

    });
</script>
  • Job 2-2: keyboard input record values, the data stored in and displayed immediately.
  • Feature 1: In addition to directly bind to a method can also be inline JavaScript statement calling the method, a function that is no longer bound directly execute JS statement at the time of the call, this method is applicable to
    the function body is very short, only function of the line.
  • Feature 2: Using the keyword Vue e v e n t it table Show J a v a S c r i p t v a l u e event, which represents the default event automatically generated JavaScript objects, it saves a lot of important information, such as the target element of the event and so on. And here, the target element is the input box, input box has a value attribute, it is the source of user input values, you can target by means of this event ( Event) to access its target element (target), then access its properties (value),
    and assigned to the variable myValue.
  • If you do not use inline mode, you can bind an event in this function, then $ event passed as parameters to the same
    method to access value in the event function and assigned to myValue, the same effect.
<script src="vue.js"></script>
<div id="app">

    <input v-on:keydown = "myValue = $event.target.value" type="text"/>
    <p>{{myValue}}</p>

</div>
<script>
    new Vue({
        el: "#app",
        data: {
            myValue: ''
        }
    });
</script>
  • Job 2-3: keyboard input record values, stored in the data, but the display is updated only press enter.
  • This question is very simple, add a title on the basis of .enter on it
<script src="vue.js"></script>
<div id="app">

    <input v-on:keydown.enter = "myValue = $event.target.value" type="text"/>
    <p>{{myValue}}</p>

</div>
<script>
    new Vue({
        el: "#app",
        data: {
            myValue: ''
        }
    });
</script>

024- write JS code in the template .html

  • In all instances where access Vue, whether listening mouse click or output counter,
    simply go to the Vue example, you can use any valid JavaScript code, as long as it is a simple
    expression can, of course, this expression can not there are complicated if statements or for circulation.
  • This is called "inline" method call
  • Such as the example above the mouse click the button to increase numbers, because the logic is simple enough,
    we even v-onclick there did not need to be bound to any function, but it can directly
    execute a statement, that is to say when the call directly counter ++ can be written.
    Of course, if the program logic is more complex, not enough to express a single statement, so honestly
    write a function and bind to the event in as well.
  • In the template may be inserted directly into an expression such as {{counter * 2}} such expressions.
  • Of course, we have to use short "Three Expressions" This expression is a variant of the if statement, to complete judgment of the variables in a row.
<script src="vue.js"></script>
<div id="app">
    <!-- 此处取消了事件函数,直接用counter++代替 -->
    <button v-on:click="counter++">Click Me</button>
    <!-- 此处直接修改模板counter的值 -->
    <p>{{ counter * 2}}</p>
    <!-- 此处是一个三元表达式,用以判断counter的值 -->
    <p>{{ counter * 2 > 10 ? 'Greate than 10' : 'Smaller than 10'}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter: 0
        }
    });
</script>

025 use two-way binding .html

  • In some cases, we need to listen to events while at the same time, while the implementation of the updated data when
    necessary to use two-way binding.
  • Vue two-way binding is really very simple, just add a v-model on the element of listening to
  • In fact, v-bind + v-on add event function can also be used to achieve this function, it is clear that
    v-model should be simple, clear many.
<script src="vue.js"></script>
<div id="app">
    <input type = "text" v-model = "name">
    <p>{{name}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            name: ''
        }
    });
</script>

026 with the calculated properties change in response to .html

  • So far, we have learned two Vue attributes: data, methods, a data placement, a placement function, is now introducing a third attribute: computed
  • First roughly sort out what effect this example:
  • Interface has three buttons, two counters, a first counter is an increase button, the second button is a counter 1 is reduced, the third button counter is increased 2
  • Another one line of text, when the display time is greater than 5 counter1: Greater than 5, when the display counter1 is less than 5: Smaller than 5
  • Note: counter2 did not do such judgments
  • In order to monitor real-time value counter1, where the use of two types of synchronization methods, the first is to write a function result in the event methods in
  • Another way is to use computed, write an event function output
  • At first glance, the two codes are the same, and there is no difference, but the real difference is:
  • 1, on the call method, methods are written in a function call with parentheses, namely: result (this form) to call
  • 2, written on computed as a function call does not need to be like calling a function, the parentheses are omitted, the same data can be directly invoked as: output
  • In fact, for the final result, in two ways really are the same, then the question is, have methods can not it do? Why do we bother springing a computed it?
  • The answer is revealed:
  • 1, inside Vue, computed properties are based on data they rely on caching, will only be re-evaluated when its associated dependent on change, time with irrelevant data changes it will not make any moves .
  • 2, method is different, as long as the pages change (re-rendered), it will always be executed, regardless of whether the data associated with it.
  • In order to verify the above conclusion, we came alive again in the interface of a button, add a variable counter2, note that this button and variables and counter1 eight-pole could not beat relations, it is a completely separate things.
  • Press the F12 key to enter debug mode browser, observe console console output
  • Now press Increase Counter 1 or Decrease Counter 1
  • The value counter1 began to change, and the console appears: Here is Computed Here is Methods and two lines
  • This is because the change counter1 value, the trigger while the methods of the result function, and based on computed based on the output function
  • Above logic is easy to understand, make sense!
  • Now press the button Increase Counter 2, this time counter2 value begins to increase, but strangely, the console display: Here is Methods
  • Why is this? Obviously result in no one function is a relationship with counter2, why each change counter2 when the program will jump into the result function in it?
  • This confirms the conclusion we said above: "As long as the page change (re-rendered), it will always be executed, regardless of whether the data associated with it."
  • Although refresh is counter2, but please note: as long as the page is re-rendered, it will always be executed.
  • It goes without saying, if it is very complex pages, repeatedly to perform a function with independent, cost efficiency is certainly significant.
  • So we need computed attribute that deal only with relevant variables (eg counter1 in this example), and irrelevant variables (counter2) even change occurs, even if the page is re-rendered, and it will not be executed .
  • Most of the time we choose computed on the right, but sometimes we just do not want to go through some of the data cache, is to let it bluntly constantly refreshes and displays the time, select methods
<script src="vue.js"></script>
<div id="app">
    <button v-on:click="counter1++">Increase Counter 1</button>
    <button v-on:click="counter1--">Decrease Counter 1</button>
    <button v-on:click="counter2++">Increase Counter 2</button>
    <p>Counter:{{counter1}} | {{counter2}}</p>
    <!-- 注意两种调用方法是不同的 -->
    <p>Counter 1 Result: {{result()}} | {{output}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter1: 0,
            counter2: 0
        },
        computed: {
            output: function () {
                console.log('Here is Computed')
                return this.counter1 > 5 ? "Greater than 5" : "Smaller than 5"
            }
        },
        methods: {
            result: function () {
                console.log('Here is Methods')
                return this.counter1 > 5 ? "Greater than 5" : "Smaller than 5"
            }
        }
    });
</script>

027- computed attribute alternatives: observed changes .html

  • Now then add a new attribute: watch
  • Vue watch is further provided a method of processing data dependent, and the net effect is actually an example of methods and computed difference is not too much, that the different places:
  • In which we set attributes computed property (as an example of output) to be calculated, and then calculate the set property (output) of the logic function body.
  • watch is another mechanism is used, the attribute name you want to listen for the key, and this key must be data which can be found in, e.g. counter1 or counter2, the embodiment of the
    keys must be inside the attribute data the same name.
  • Define a property name and the same function in the watch, that is, when the attribute value changes
    the code to be executed, the transmission will automatically Vue value after the attribute change to the function.
  • In terms of results, since that role and computed rather watch, then we have to use the watch why not? Because the watch is executed asynchronously.
  • About what is asynchronous execution, say a few words is not clear, venue search engine
  • computed only perform synchronization tasks, that is to say when it return, you must immediately return a result
    the middle can not access the server or perform asynchronous tasks.
  • For example, you need a value, updated after two seconds, you must watch
  • Theoretically, Vue example, always use this access to its own (see the previous content), but in
    the callback closure is not, the timer function (setTimer) is an example of a typical callback closure, thus
    which can not directly access this, but with a variable should be saved first, for use in setTimer function.
  • What about the "callback closure", venue search engine
  • Of course, you can also try to watch this code into computed try to go inside, the result is only cleared once, and then the code is no longer executed.
  • In most cases, it is recommended to use computed, because it has the best speed, but in the implementation of asynchronous tasks, we can only choose to watch
<script src="vue.js"></script>
<div id="app">
    <button v-on:click="counter1++">Increase Counter 1</button>
    <p>Counter:{{counter1}}</p>
</div>
<script>
    new Vue({
        el: "#app",
        data: {
            counter1: 0,
        },
        watch: {
            counter1: function (value) {
                // 注意:回调闭包中不允许直接使用this
                // 因此此处需要先用一个变量vm来保存this
                var vm = this;
                setTimeout(function () {
                    vm.counter1 = 0
                }, 2000)

            }

        }
    });
</script>

Guess you like

Origin blog.csdn.net/rockage/article/details/89644003