My Vue study notes (a)

My Vue study notes

MVVM idea

MVVM is a Model-View-ViewModel shorthand, namely: Model - View - ViewModel
model refers to the back-end data transfer of
view is the page we see the
view of the model is the core part of the MVVM thought, and it links View Model as a communication bridge between them, it has two directions: one is converted to the Model View, i.e., the rear end of the data transfer page is converted into a saw, two sucked into Model View, i.e. the user operating on the page content into back-end data, these two functions is achieved through data binding and DOM event listeners, we call two-way data binding . as the picture shows:


In general: the view and model layer by layer ViewModel communication, when data changes, this change ViewModel able to listen to the data, and then update the view layer by notifying the corresponding page; When the user operates the View layer, it is possible to ViewModel listens to change the view, and then make changes to the notification data, which is thought MVVM, while Vue.js using MVVM idea to build both a lightweight and fast development of efficient and powerful framework.

Create an instance, data binding, commands and events

Create an instance of

vue method creates an instance of the following:

    <div id="app">
        {{myData}}
    </div>
    <script>
        var vueApp = new Vue({
            el:'#app',
            data:{
                myData:'Hello World'
                myData2:'Fuck World'
            }
        });
    </script>
复制代码

El code and data are vue instance attributes, el DOM elements for which a specified page already exists to mount Vue example, data is bound to require two-way data Vue.

Data Binding

After loading, we can use vue实例.$vue实例的属性the syntax to obtain attribute vue instance, for example: vueApp.$elaccessing data attributes is different, we can directly use vue实例.data的属性名the syntax to access, for example:vueApp.myData

Lifecycle hook

vue lifecycle hook method is defined to perform in a certain stage of the life cycle of the Vue objects. Vue from the initialization instance objects, until it is destroyed, the object will follow the different stages of life, the specific content I cut a very famous lifecycle hook map:


Specifically:

  1. beforeCreate: Create a hook function before vue examples
  2. created: created a vue example, but not mounted onto the page DOM elements
  3. beforeMount: begin to mount
  4. mounted: mounted to the compiled html page and mounted executed only once in the entire life cycle
  5. beforeUpdate
  6. updated
  7. beforeDestroy: hook function previously performed vue instance destroyed
  8. Hooking function executes instance destroyed

vue life cycle has many stages, but we are the most commonly used of these three stages:

  1. created
  2. mounted
  3. beforeDestroy

for example:

var vueApp = new Vue({
        el:'#app',
        data:{
            myData:'Hello World'
        },
        created:function () {
            alert('vue实例创建完毕了,但是还没有挂载到DOM元素上');
        },
        mounted:function () {
            alert('vue实例已经挂载到DOM上了');
        }
    });
复制代码

For the above example the page, the browser opens, will first pop-up "to create a finished vue example, but not yet mounted to the DOM element" such message, created for this stage it is, in fact, has been completed vue examples creation, but did not mount to the DOM element, then pop up "vue instance has been mounted onto the DOM" prompt box, mounted the stage to create an instance of vue mount after the DOM calls, our first a business logic usually started here, for beforeDestory stage, by word meaning can also know that this is the stage before vue example of the destruction, tied by a number of events will be listening solution at this stage.

Interpolation Text

For this example is concerned, we will see the words Hello World on the page, in html, we write such a syntax:

<div id="app">
    {{myData}}
</div>
复制代码

This syntax is text Vue interpolation syntax, which supports a single expression, note that only a single expression:

{{1<0 ? myData:myData2}}
这是三元运算符表达式,因为它属于单个表达式
所以这是合法的,我们会在页面上看到Fuck World
{{var a = 6}}
注意:这是非法的
var a = 6 是一个声明表达式 + 一个赋值表达式
我们提到过 Vue 的文本插值语法只支持单个表达式
所以 这句话会报错
复制代码

filter

vue.js supports adding a small pipe characters in {} interpolated tail "|" data filtering, often used for text formatting, such as all capital letters, separated by commas currency one thousand etc., but also supports the filter series writing, mass participation, and so on. Let's look at an example:
page displays the current time in real time:

<div id="app">
        {{currentDate | format}}
    </div>
    <script>
        function formatTime(value) {
            return value <10 ? '0'+value : value;
        }
        var vueApp = new Vue({
            el:'#app',
            data:{
                currentDate: new Date()
            },
            filters:{
                format:function (currentDate) {
                    var date = new Date(currentDate);
                    var year = date.getFullYear(); // 获取当前年
                    var month = formatTime(date.getMonth()+1); // 获取当前月(需要+1)
                    var days = formatTime(date.getDate()); // 获取当前天
                    var hours = formatTime(date.getHours()); // 获取当前小时
                    var minutes = formatTime(date.getMinutes()); // 获取当前分钟
                    var seconds = formatTime(date.getSeconds()); // 获取当前秒

                    return '当前时间为:'+year+'年'+month+'月'+days+'日'+hours+'时'+minutes+'分'+seconds+'秒'
                }
            },
            mounted:function () {
                this.timer = setInterval(()=>{
                    this.currentDate = new Date();
                },1000)
            },
            beforeDestroy:function () {
                window.clearInterval(this.timer);
            }
        });
    </script>
复制代码

We can also pass parameters to filter, we will make a small change of code:

<div id="app">
        {{currentDate | format('当前时间为',':')}}
    </div>
    <script>
        function formatTime(value) {
            return value <10 ? '0'+value : value;
        }
        var vueApp = new Vue({
            el:'#app',
            data:{
                currentDate: new Date()
            },
            filters:{
                format:function (currentDate,arg1,arg2) {
                    var date = new Date(currentDate);
                    var year = date.getFullYear(); // 获取当前年
                    var month = formatTime(date.getMonth()+1); // 获取当前月(需要+1)
                    var days = formatTime(date.getDate()); // 获取当前天
                    var hours = formatTime(date.getHours()); // 获取当前小时
                    var minutes = formatTime(date.getMinutes()); // 获取当前分钟
                    var seconds = formatTime(date.getSeconds()); // 获取当前秒

                    return arg1+arg2+year+'年'+month+'月'+days+'日'+hours+'时'+minutes+'分'+seconds+'秒'
                }
            },
            mounted:function () {
                this.timer = setInterval(()=>{
                    this.currentDate = new Date();
                },1000)
            },
            beforeDestroy:function () {
                window.clearInterval(this.timer);
            }
        });
    </script>
复制代码

We have added a parameter in a filter, before and got the same results. It notes that there is: a filter function corresponding to the first incoming value "|" attribute value before the data is, i.e. in the present example: currentDate, rather than a parameter, the parameter is passed in the second and subsequent transfer of the value of the function value. Filters can also be used simultaneously "written series", such as: {{currentDate | filter1 | filter2 | filter3 }}The process of the filter will be executed sequentially, and they are defined in the properties among the filters vue.

Instruction and events

Support instruction operation is one of the advantages vue framework, which is the most common template vue a feature, eliminating the need for complex DOM API, and its easy to remember and understand. Next, let's understand some simple instruction operation:

  1. v-text

    v-text function is to parse the text and its specific role text Interpolation {} is the same as a hair

  2. v-html

    The content analysis into html

  3. v-bind

    Dynamically updated elements on HTML, such as id, class, etc.

  4. v-on

    It used to bind event listeners

Next we are still by way of example, to recognize these simple instruction event.

    <style>
        .active{
            background: red;
            height: 1em;
        }
    </style>
---------------------------------------------------------------
    <div id="app">
        v-text: <br>
        {{apple}} <br>
        <!--v-text 的作用和文本插值 是一样的-->
        <span v-text="apple"></span>
        v-html: <br>
        <span v-html="banana"></span> <br>
        v-bind: <br>
        <div v-bind:class="className"></div>
        v-bind的简写格式: <br>
        <div :class="className"></div>
        v-on: <br>
        <button v-on:click="plusOne">{{originalNum}}</button>
        <br>
        v-on的简写格式: <br>
        <button @click="plusOne">{{originalNum}}</button>
    </div>
    <script>
        var app = new Vue({
            el:'#app',
            data:{
                apple:'苹果',
                banana:'<span style="color: yellow;">香蕉</span>',
                className:'active',
                originalNum:0
            },
            methods:{
                plusOne:function () {
                    this.originalNum = this.originalNum + 1;
                }
            }
        });
    </script>
复制代码

As part of html content, abbreviated format for the v-bind and v-on instruction has a corresponding two, as in the example:

<div v-bind:class="className"></div>
可以简写为:
<div :class="className"></div>


<button v-on:click="plusOne">{{originalNum}}</button>
可以简写为:
<button @click="plusOne">{{originalNum}}</button>

复制代码

Computed Property

Look at an example: we want to achieve a function which reverses the string, the string for '123,456,789' we want the string becomes: '321,654,987', the following exemplary procedure:

<div id="app">
    {{text.split(',').map((e)=>{return e.split('').reverse().join('')}).join(',')}}
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            text:'123,456,789'
        }
    });
</script>
复制代码

We see this program heart must sell a mom approved, although the program is no problem, also in line with text interpolation syntax, but it looks like is that headache, and write code that is not good for maintenance. We can do a content optimization, creating a function and function on the methods which attributes:

<div id="app">
    <!--将'123,456,789' 这串字符串 变为 '321,654,987'-->
    令人头痛的代码: <br>
    {{text.split(',').map((e)=>{return e.split('').reverse().join('')}).join(',')}} <br>
    methods属性内的方法: <br>
    {{reverseMethod()}} <br>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            text:'123,456,789'
        },
        methods:{
          reverseMethod:function () {
              // ['123',456,'789']
              return this.text.split(',').map((e)=>{
                  return e.split('').reverse().join('');
              }).join(',');
          }
        }
    });
</script>
复制代码

In addition to the method defined in the methods and call, we can also use the calculated property :

<div id="app">
    <!--将'123,456,789' 这串字符串 变为 '321,654,987'-->
    令人头痛的代码: <br>
    {{text.split(',').map((e)=>{return e.split('').reverse().join('')}).join(',')}} <br>
    methods属性内的方法: <br>
    {{reverseMethod()}} <br>
    计算属性: <br>
    {{reverseText}}
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            text:'123,456,789'
        },
        methods:{
          reverseMethod:function () {
              // ['123',456,'789']
              return this.text.split(',').map((e)=>{
                  return e.split('').reverse().join('');
              }).join(',');
          }
        },
        computed:{
            reverseText:function () {
                return this.text.split(',').map((e)=>{
                    return e.split('').reverse().join('')
                }).join(',');
            }
        }
    });
</script>
复制代码

We define the method in a computed attribute vue example of which, at first glance, and methods and there is no difference, in fact, something calculated properties can be achieved in methods of approach can be achieved, but both also have differences. Specific differences, we read after another example, again introduced:
the function of this example is the sum of the price of the shopping cart to calculate the specific code as follows:

<div id="app">
    {{prices}}
</div>
<script>
    var app2 = new Vue({
        el:'#app2',
        data:{
            msg:'两个购物车的价格总和为:'
        }
    });
    var app = new Vue({
       el:'#app',
       data:{
           // 购物车1
           package1:[
               {
                   name:'iphone',
                   price:6999,
                   count:2
               },
               {
                 name:'ipad',
                 price:3299,
                 count:2
               }
           ],
           // 购物车 2
            package2:[
                {
                    name:'XiaoMi',
                    price:999,
                    count:6
                },
                {
                    name:'ipod',
                    price:1099,
                    count:2
                }
            ]
       },
       computed:{
           prices:{
               get:function () {
                   var prices = 0;
                   //  第一个购物车的价格总和
                   for(var i = 0;i<this.package1.length;i++){
                       prices += this.package1[i].price * this.package1[i].count;
                   }

                   // 第一个购物车与第二个购物车的价格总和
                   for(var j = 0; j<this.package2.length;j++){
                       prices += this.package2[j].price * this.package2[j].count;
                   }

                   return app2.msg+prices;
               },
               set:function (options) {
                   if(options.package === 'package1'){
                       for(var i = 0;i<this.package1.length;i++){
                           if(this.package1[i].name === options.name){
                               this.package1[i].price = options.price;
                               this.package1[i].count = options.count;
                               break;
                           }
                       }
                   }else if(options.package === 'package2'){
                       for(var i = 0;i<this.package2.length;i++){
                           if(this.package2[i].name === options.name){
                               this.package2[i].price = options.price;
                               this.package2[i].count = options.count;
                               break;
                           }
                       }
                   }
               }
           }
       }
    });
</script>
复制代码

Each attribute has a calculated getter and setter methods, when we just call a method of calculating an attribute name, actually calls the get method of the property, when it is necessary to set some parameters, we can also provide a set manually modify the method of calculating properties. Further, in the present example, we can see that the properties calculated current prices depending not only on objects but also on vue other instances, although not app2 mounted on the DOM, but the results show that calculation performed may depend on the properties of other instances . Result codes are as follows:


We can set the parameters required by the method set changes:


When the modification is completed, the page will be updated in real time data:


We look back and talk about the next method and calculation methods in the property What differences:

The method of calculating the properties and methods

We first look at an example:

<div id="app">
    {{text}} <br>
    {{getNow()}} <br>
    {{now}} <br>

</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            text:666
        },
        methods:{
            getNow:function () {
                return Date.now();
            }
        },
        computed:{
            now:{
                get:function () {
                    return Date.now(); // 获取 1970年 至现在的时间戳
                }
            }
        }
    });
</script>
复制代码

We are methods and calculation methods are defined in acquiring properties in 1970 until now the time stamp function, the resulting code runs as follows:


Now, I do a little of the content of text changes:


After we changed the text data, the page will naturally change happen, but we found:
the content is not just text has undergone changes, getNow method methods of rendering on the page html has also undergone a change:


Why is this so? This would involve a cache inside the calculation properties. For calling the method, as long as the page is re-rendered, then the method will be executed, note that I mentioned are just re-rendering the page, if not render it, the method is not self-executing, calculated attribute is different, regardless of page whether rendering occurs, as long as the property is calculated dependent data has not changed, then it will never change. Calculating the difference between the properties and methods of both methods is dependent on what is different is calculated based on its dependent attribute data caching, when it depends on a difference of the data, it will change, and the methods are not cached, when page undergone re-rendering, the method will be executed. In the above, what methods mentioned method for calculating the properties that can be achieved can be achieved, then the choice of how to use them? In fact, think about it too can come up with a result, when we need a lot of computing, because the data calculate the cost of memory, we need the data cache, then it should be used to calculate property.

v-bind of class and style bindings

The role of v-bind only can be described in one sentence, that is, the binding properties of living, we have to look at a simple example:

<div id="app">
    <a v-bind:href="url">链接</a>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            url:'http://www.baidu.com'
        }
    });
</script>
复制代码

Click after the jump page will be connected to baidu.

v-bind the class bindings

v-bind binding class object syntax

See Example:

    <style>
        .red{
            background: red;
        }
        .blue{
            background: blue;
        }
    </style>
--------------------------------------------------
<div id="app">
    v-bind绑定对象: 对象的key是类名,对象的value是布尔值<br>
    <button v-bind:class="{red:isRed,blue:isBlue}" v-on:click="transColor">clickMe</button>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            isRed:true,
            isBlue:false,
        },
        methods:{
            transColor:function () {
                this.isRed = !this.isRed;
                this.isBlue = !this.isBlue;
            }
        }
    });
</script>
复制代码

This example is the function of a button press down energy conversion of colors, while v-bind: class using the object syntax, key value for the object name of the object class is boolean If true then binding this class name, if it is false, and no such name association.

v-bind bind calculate property syntax

See Example:

    <style>
        .red{
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
-----------------------------------------------
<div id="app">
    v-bind绑定计算属性: 计算属性返回的也是对象 key为类名 ; value为 布尔值 <br>
    <div v-bind:class="computedClass"></div>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            isRed:true,
        },
        computed:{
            computedClass:function () {
                return {
                    red:'isRed'
                }
            }
        }
    });
</script>
复制代码

Example v-bind: class attribute calculation bound, but even to calculate attribute, the result is returned object key in the object class name, value is a Boolean value, supra true value when the value, the element carrying this class, when the value is false, element not carrying the class

v-bind binding class array syntax

See Example:

    <style>
        .first{
            font-size: 32px;
            color: red;
        }
        .second{
            background: #000;
        }
    </style>
---------------------------------------
<div id="app">
    绑定class数组语法:数组中的成员为data中的属性,这些属性直接对应类名 <br>
    <div v-bind:class="[classOne,classTwo]">VUE is cool!</div>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            classOne:'first',
            classTwo:'second'
        }
    });
</script>
复制代码

v-bind array Syntax class binding compared to more simple in terms of the foregoing, the array of data members attributes corresponding to the class name directly, by way of example should not be difficult to understand -

v-bind bind inline style

In addition to the more commonly used class binding, v-bind inline styles can also bind

<div id="app">
    绑定内联样式:对象语法,key 代表style的属性,value代表属性对应的值 br>
    <div v-bind:style="{'color':color,'fontSize':fontSize}">VUE is cool!</div>
</div>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            color:'red',
            fontSize:'32px'
        }
    });
</script>
复制代码

In addition to this object syntax, bind inline style also supports the "array" syntax, but said that this syntax is stupid, because no one would write separate style, so I will not here listed. Note that the css property names use camel named, separated by dashes or named, but there is still the recommended wording Camel ~ ~ ~ ~

Guess you like

Origin blog.csdn.net/weixin_33736649/article/details/91398289