Vue Learning Records

Keywords: Programming Vue Attribute

Vue example

Creation of Vue instances

var vm = new Vue({
  // option
})

Data freeze

Using Object.freeze(), this prevents modification of existing attributes and means that the response system can no longer track changes.

var obj = {
  foo: 'bar'
}

Object.freeze(obj)

new Vue({
  el: '#app',
  data: obj
})
<div id="app">
  <p>{{ foo }}</p>
  <!-- There `foo` No updates! -->
  <button v-on:click="foo = 'baz'">Change it</button>
</div>

$

In addition to data attributes, Vue instances also expose some useful instance attributes and methods. They all have a prefix of $, which distinguishes them from user-defined attributes. For example:

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

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

// $watch is an example method
vm.$watch('a', function (newValue, oldValue) {
  // This callback will be called after the `vm.a'change
})

Later you can be in API reference A complete list of instance attributes and methods is available.

Instance lifecycle hook

such as created Hooks can be used to execute code after an instance is created:

new Vue({
  data: {
    a: 1
  },
  created: function () {
    // ` this `points to the vm instance
    console.log('a is: ' + this.a)
  }
})
// => "a is: 1"

There are also other hooks that are called at different stages of the instance life cycle, such as mounted,updated and destroyed . The this context of the lifecycle hook points to the Vue instance that invokes it.

The following figure shows the life cycle of the example. You don't need to understand everything right away, but as you continue to learn and use it, its reference value will become higher and higher.

Template grammar

interpolation

text

<span>Message: {{ msg }}</span>

v-once

through the use of v-once instruction You can also perform one-time interpolation, and when the data changes, the contents of the interpolation will not be updated. But be aware that this affects other data bindings on that node:

<span v-once> This will not change: {msg}</span>

v-html

<span v-html="rawHtml"></span></p>

v-bind:

<div v-bind:id="dynamicId"></div>
<button v-bind:disabled="isButtonDisabled">Button</button>

If the value of isButtonDisabled is null, undefined or false, the disabled feature will not even be included in the rendered < button > element.

JS expression

{{ number + 1 }}

{{ ok ? 'YES' : 'NO' }}

{{ message.split('').reverse().join('') }}

<div v-bind:id="'list-' + id"></div>

Each binding can only contain a single expression, so the following example will not take effect.

<!-- This is a statement, not an expression. -->
{{ var a = 1 }}

<!-- Flow control will not work either. Use ternary expressions -->
{{ if (ok) { return message } }}

instructions

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

Here, the v-if instruction inserts/removes < p > elements based on the truth or falsity of the value of the expression seed.

parameter

Some instructions can receive a "parameter" that is coloned after the instruction name. For example, the v-bind instruction can be used to update HTML features responsively:

<a v-bind:href="url">...</a>

Here href is a parameter that tells the v-bind instruction to bind the href characteristics of the element to the value of the expression url.

<a v-on:click="doSomething">...</a>

Abbreviation

<!-- Complete grammar -->
<a v-bind:href="url">...</a>

<!-- Abbreviation -->
<a :href="url">...</a>

<!-- Complete grammar -->
<a v-on:click="doSomething">...</a>

<!-- Abbreviation -->
<a @click="doSomething">...</a>

Compute properties and listeners

computed attribute

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // getter for calculating attributes
    reversedMessage: function () {
      // ` this `points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
})

Computing Attribute Cache vs Method

The same effect is achieved by invoking methods in expressions:

<p>Reversed message: "{{ reversedMessage() }}"</p>
// In components
methods: {
  reversedMessage: function () {
    return this.message.split('').reverse().join('')
  }
}

We can define the same function as a method rather than a computational property. The end result of the two approaches is exactly the same. However, the difference is that computational attributes are cached based on their dependencies.

The following computational properties will no longer be updated

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

Computing attributes vs listening attributes

computed: {  /*computed The computed attribute defined in this section indicates that an attribute is computed from other attributes. If firstName or lastName is unchanged, it will directly use the cached results used last time when it is used again.*/
    fullName : function(){
        return this.firstName + ' ' + this.lastName;
    }
}

setter for calculating attributes

By default, getter is the only computational attribute, but you can also provide a setter if you need to:

// ...
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 when you run vm. fullName ='John Doe', setter will be called and vm.firstName and vm.lastName will be updated accordingly.

Listener watch

The watch option provides a more general way to respond to changes in data

vm.$watch API.

Class and Style binding

We can pass an object to v-bind:class to dynamically switch classes:

<div v-bind:class="{ active: isActive }"></div>

The above grammar indicates that the existence of the active class will depend on the data attribute isActive.

You can dynamically switch multiple classes by passing more attributes into the object. In addition, the v-bind:class instruction can coexist with the normal class attribute. When there are the following templates:

<div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>

And the following data:

data: {
  isActive: true,
  hasError: false
}

The results are rendered as follows:

<div class="static active"></div>

Binding data objects need not be defined inline in templates:

<div v-bind:class="classObject"></div>
data: {
  classObject: {
    active: true,
    'text-danger': false
  }
}

The rendering results are the same as above.

We can also bind the computed properties of a return object here. This is a common and powerful model:

<div v-bind:class="classObject"></div>
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'text-danger': this.error && this.error.type === 'fatal'
    }
  }
}

Array grammar: We can pass an array to v-bind:class to apply a list of classes:

<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

Render as:

<div class="active text-danger"></div>

If you also want to switch class es in the list according to conditions, you can use ternary expressions:

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

It's a bit cumbersome to write this when there are multiple conditional class es. So object grammar can also be used in array grammar:

<div v-bind:class="[{ active: isActive }, errorClass]"></div>

Posted by Avalanche on Thu, 16 May 2019 07:47:01 -0700