vue.js study notes 2

First, the vm object

1. The core of vue.js is the data-driven view, but how does the data drive the view? Putting a bunch of data there will not do anything, it has to go through our View Model (view model) to manipulate the view.

The following is the view model

    var vm = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })

The data is placed in the vm, and various directives are placed in the view. We can use the vm as the unconnected, and change the view by changing the data~

2. What properties and methods does the vm object have?

This data is reactive

When a vue instance (called vm) is created, vm will add all the properties in vm's data object to Vue's responsive system. When these properties change, the view will "respond", that is, become new value
    var data = { a: 1 }
    var vm = new Vue({
      data: data
    })
    vm.a === data.a // -> true
    // 设置vm数据会使原来的数据发生改变
    vm.a = 2
    data.a // -> 2
    // ... 反过来亦然
    data.a = 3
    vm.a // -> 3

That is, when vm.a changes, data.a also changes, and when data.a changes, vm.a also changes (which can be understood as two-way binding~)

Notice! ! ! Only the attributes in the data when the instance is created are responsive. If a new attribute is added after creation, the change of the newly added attribute will not trigger any view update, so if you want the attribute to be responsive, you You should assign an initial value to the property when you create an instance~

How to get other attributes through vm

    vm.$el === document.getElementById('app') // -> true
    vm.$data === data // -> true
    vm.$data.message ==='Hello Vue!' // -> true
This $ symbol represents the real properties of vm. The attributes that come with Vue should be added with the $ symbol, and if it is a custom attribute, such as the above vm.a, it can be omitted.

In addition to data properties, Vue instances also expose some useful instance properties and methods. They are all prefixed $to distinguish them from user-defined properties.


var data = { a: 1 }
var vm = new Vue({
  el: '#example',
  data: data
})

vm.$data === data // => true
vm.$el === document.getElementById('example') // => true

// $watch 是一个实例方法
vm.$watch('a', function (newValue, oldValue) {
  // 这个回调将在 `vm.a` 改变后调用
})



instance lifecycle hooks

Behind


new Vue({
  data: {
    a: 1
  },
  created: function () {
    // `this` 指向 vm 实例
    console.log('a is: ' + this.a)
  }
})
// => "a is: 1"




Second, the syntax of binding data in Html

The way Vue controls the view is to insert the data control directly in the html. Is this very similar to php? Simple and intuitive.

In general, there are two ways to insert data controls in html, one is { {}}double curly braces, the other is directivesimilar to v-on:clickthis writing method, we have seen both writing methods before, here we will review and strengthen it;

1. Double curly braces
    <span v-once>This will never change: {
   
   { msg }}</span>

1) The data in double curly braces is responsive by default. If you want to disable responsiveness, you can write v-once. In this way, msg is changed in the view, and the content of this span will not change.

< p > Use double curly braces: {
    
   { rawHtml }} </ p > 
< p > Use v-html directive: < span  v-html = "rawHtml" > </ span > </ p >

2) Double curly brackets will interpret the data as normal text, not HTML code. In order to output real HTML, you need to use the v-htmldirective :

3) Run expressions in { {}}: Vue.js provides full JavaScript expression support.

    {
   
   { number + 1 }}
    {
   
   { ok ? 'YES' : 'NO' }}
    {
   
   { message.split('').reverse().join('') }}

It generally expresses the operation relationship; if the operation is very simple and one-time, you can use this short writing method without filter; Note: You can only write a single-line expression in { {}}, not multiple lines , and more Complicated operations We will introduce solutions later;
the following are illegal:

 
 
  1. <!-- 这是声明,不是表达式 -->
  2. { { var a = 1 }}
  3. <!-- 条件语句不适用,你可以使用三元运算表达式 -->
  4. { { if (ok) { return message } }}

4) Filter

For some data, such as a decimal, you always want to format it as an integer when the html is displayed. At this time, you need to add a fixed method

    {
   
   { float_number | toInt }}
The front is a decimal variable, and the back toInt is a method; let's see how to define this method in vm:
    new Vue({
      el: '#app',
      data: {
        float_number: 3433.45
      },
      filters: {
        toInt: function (value) {
          return parseInt(value);
        }
      }
    })

See that property keyword of filters, a filter is just a method and will be executed automatically.

The final result in the html will be 3433.

Since filters are methods, of course you can add parameters:

    {
   
   { message | filterA 参数1,参数2 }}

Parameters are not enclosed in parentheses, but directly written with spaces after them. Different parameters are separated by commas. A specific value or an expression can be written in the parameter here.

2.Directives

Directives are special attributes v-prefixed with . The value of the directive attribute is expected to be a single JavaScript expression ( v-forwith the exception, we'll discuss that later). The responsibility of the directive is to responsively act on the DOM when the value of the expression changes, with its associated effects. Recall the examples we saw in the introduction:

< p  v-if = "seen" > Now you see me </ p >

Here, the v-ifinstruction seenwill insert/remove <p>elements based on the true or false value of the expression .

Directive is v-a special html attribute of the form , which is the connection point between vm and html.

We have already learned 2 sums v-for, v-onnow let’s strengthen them, learn a little more, and we will come into contact with more later. This is how the vue tutorial is, step by step and repeated reinforcement.

1) v-text (normal)

    <div v-text="stringText"></div>

equal

    <div>{
   
   {stringText}}</div>

2) v-html (normal)

there are

3) v-on (with parameters)

Some directives can take a "parameter", shown with a colon after the directive name

Where v-on is used to listen to DOM events

如:v-on:click="doSth"

v-on: Monitored event name="function name"

4) v-bind (with parameters)

v-bindDirectives can be used to reactively update HTML attributes:

v-bind:html attribute="attribute value"

如:v-bind:id="idName"

4. Modifiers

Modifiers are special suffixes designated by half-width periods .to indicate that an instruction should be bound in a special way. For example, the .preventmodifier tells the v-ondirective to be called for the triggered event event.preventDefault():

You'll see other examples of modifiers in the v-onfollowing exploration of functions such as and .v-for

We see that there is one after the submit event .prevent, which actually represents event.preventDefault(); this kind of dotted writing is a modifier, which generally has some special functions.

Let’s get familiar with the writing method first, and we will introduce more modifiers later;
    <form v-on:submit.prevent="onSubmit"></form>

3. Computed properties and data monitoring

1. Computed properties

Although you can put a JavaScript statement inside { { }}, but putting too much logic in it will make the statement difficult to read and maintain

E.g:

<div id="example">
  {
   
   { message.split('').reverse().join('') }}
</div>

So, for any complex logic, you should use computed properties

var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    
    
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})

But this function, the above function can be achieved by calling the function~ But why use the computed property first?

Calculated attribute ===> data attribute, it depends on the data in data, if the data in data does not change, because of the dependence, can we cache the calculated attribute~ Calculated attributes can be automatically cached according to the change of the data attribute source , and the methods in methods are run once every time~ This is why the computed property is used first~

Such as:

    computed: {
      now: function () {
        return Date.now()
      }
    }

If you define such a computed property that does not depend on any data source, it will not change over time, it will directly cache the first data, only when the data source is associated and the data source changes, the cache will update~

In contrast, whenever a re-render is triggered, calling the method will always execute the function again whenever a re-render is triggered.

Why do we need caching? Suppose we have a computationally expensive property A that needs to traverse a huge array and do a lot of calculations. Then we may have other computed properties that depend on A. Without caching, we would inevitably execute A 's getter multiple times! If you don't want caching, use methods instead.

When the now method is called in the console, the now is always the data that the browser has just refreshed, and it is not updated because it is called in the console~

This is the biggest difference between computed properties and methods

2. Computed properties vs listening properties

Vue provides another way to observe and respond to Vue's data changes: listening properties --- watch

When there is data that needs to change with other data changes, watches are easily abused

Such as:

<div id="demo">{
   
   { fullName }}</div>

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

In order to get the fullName, you need to listen to the changes of firstName and lastName, and the processing of the two is repeated. In fact, at this time, you should use the computed property

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

Much better, isn't it?

3. Setters for computed properties

Computed properties only have getters by default, that is, they can only return one processed data, but you can provide a setter when needed

// ...
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
// ...
Now vm.fullName = 'John Doe' when , the setter will be called, vm.firstName and vm.lastName will be updated accordingly.



Fourth, Class and style binding

    <div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
We see that the data binding is a bit special, here is an object , the key inside is the name of the class , and the value is the binding data . When the binding data is true, the class will be rendered into html;
pay attention to the key Adding '' or not adding '' here is the same.



1) This added class name can coexist with the original class name~

2) Directly use the object to bind



This method is recommended if you want to control more complex class display. Carefully compare the two writing methods, you will find that the class is the data variable .

Then you can control whether to add such names by controlling true and false

3) Use an array (do not judge whether to add or not, but directly add multiple class names)












Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324359840&siteId=291194637