Vue instance · new Vue()

16, Vue instance

1. Create a Vue instance

Each Vue application starts by creating a new Vue instance with the Vue function:

var vm = new Vue({
  // option
  //When creating a Vue instance, you can pass in an option object.
})

Although it does not fully follow the MVVM model, Vue's design is also inspired by it. Therefore, the variable name VM (short for ViewModel) is often used in documents to represent Vue instances.

A Vue application consists of a root Vue instance created through new Vue and an optional nested and reusable component tree. For example, the component tree of a todo application can be as follows:

Root instance
└─ TodoList
   ├─ TodoItem
   │  ├─ TodoButtonDelete
   │  └─ TodoButtonEdit
   └─ TodoListFooter
      ├─ TodosButtonClear
      └─ TodoListStatistics

Now, you just need to understand that all Vue components are Vue instances and accept the same option object (except for some root instance specific options).

2. Data and methods

When a Vue instance is created, it adds all the properties in the data object to the Vue's responsive system. When the values of these properties change, the view will produce a "response", that is, the match is updated to the new value.

// Our data object
var data = { a: 1 }

// The object is added to a Vue instance
var vm = new Vue({
  data: data
})

// Get the property on this instance
// Return the corresponding field in the source data
vm.a == data.a // => true

// Setting property will also affect the original data
vm.a = 2
data.a // => 2

// ... and vice versa
data.a = 3
vm.a // => 3

When these data changes, the view is re rendered. It is worth noting that only properties that already exist in data when the instance is created are responsive. That is, if you add a new property, such as:

vm.b = 'hi'

Then changes to b will not trigger any view updates. If you know you will need a property later, but it is empty or nonexistent at first, you only need to set some initial values. For example:

data: {
  newTodoText: '',
  visitCount: 0,
  hideCompletedTodos: false,
  todos: [],
  error: null
}

The only exception here is to use object Free (), which prevents the modification of existing properties, also 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` Not updated! -->
  <button v-on:click="foo = 'baz'">Change it</button>
</div>

In addition to data properties, Vue instances also expose some useful instance properties and methods. They are prefixed with $, to distinguish them from user-defined properties. 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 instance method
vm.$watch('a', function (newValue, oldValue) {
  // This callback will be in ` VM A` call after change
})

3. Instance life cycle hook (key)

When each Vue instance is created, it goes through a series of initialization processes -- for example, setting data listening, compiling templates, mounting the instance to the DOM and updating the DOM when the data changes, etc. At the same time, some functions called life cycle hooks will be run in this process, which gives users the opportunity to add their own code at different stages.

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 invoked 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.

Do not use arrow functions on option property or callback, such as
created: () => console. Log (this. A) or VM$ watch('a', newValue => this.myMethod()).

Because the arrow function does not have this, this will be used as a variable to search the upper lexical scope until it is found,

Often leads to Uncaught TypeError: Cannot read property of undefined or uncaught typeerror: this Mymethod is not a function.

4. Life cycle diagram (key)

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

Tags: Vue.js

Posted by lentin64 on Sat, 14 May 2022 14:34:13 +0300