zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Vue Study Notes (2) - Vue Instances and Template Syntax

1. Vue Instances#

1. Creating Vue Instances#

A Vue instance should be created as a root instance using new Vue, and all Vue components are actually Vue instances.

var vm = new Vue({
  ...
})

When an instance is created, the properties in the data object are added to the Vue's reactive system, and when the values change, the view will also change.

var data = {a: 1}

var vm = new Vue({
  data: data
})

At this point, entering vm.a == data.a in the console will return true, indicating that the data variable has been assigned to the data object in the Vue instance.

At the same time, manipulating the data of both objects will affect the other.

vm.a = 2
// data.a = 2

data.a = 3
// vm.a = 3

When the data changes, the view will be re-rendered. If a new property is added after the Vue instance is created, it will not be added to the reactive system.

If you know that a property will be added later, but it does not exist or is empty at the beginning, you need to set some initial values.

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

When using the Object.freeze() method, the data cannot be modified to cause a view change.

The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, existing properties from being changed, and prevents the prototype from being changed. freeze() returns the same object that was passed in as a parameter.

<div id="app">{{message}}</div>

<script>
  var data = {message: 'hello,wolrd'}
  Object.freeze(data)

  var vm = new Vue({
    el: '#app',
    data: data
  })
</script>

Changing the value of vm.message in the console will result in an error because the data object has been frozen and cannot be changed.

vue-learn-2.jpg

vm.$data

Represents the data object observed by the Vue instance.

console.log(vm.$data)
// Returns the data object in array form
var data = { a: 1 }
var vm = new Vue({
  el: '#app',
  data: data
})

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

2. Lifecycle Hooks#

Each instance goes through an initialization process when it is created, such as setting up data observation, compiling templates, mounting the instance to the DOM, updating the DOM, etc.

During this process, there are some special methods called lifecycle hooks that can be used to add custom code at different stages.

vue-learn-3.png

For example, the created hook can be used to execute code after an instance is created.

new Vue({
  data: {
    a: 1
  },
  created: function () {
    console.log('a is: ' + this.a)
  }
})
// "a is: 1"

this is used to refer to the Vue instance.

However, do not use arrow functions on properties or callbacks, such as created: () => console.log(this.a), because arrow functions do not have the concept of this. They treat this as a variable and keep looking for it in the parent scope, often resulting in errors like Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.

2. Template Syntax#

1. Interpolation#

The simplest form is:

<div id="app">{{message}}</div>

<script>
    var app = new Vue({
        el: "#app",
        data: {
            message: 'hello,world'
        }
    })
</script>

...

The following code binds a disabled attribute to the input, but the attribute is only rendered if ok is true. It is similar to v-if, but this syntax is only for attributes.

<div id="app">
    <input type="text" v-bind:disabled="ok">
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            message: 'hello,wolrd',
            ok: false
        }
    })
</script>

JavaScript expressions can also be used in template syntax

<div id="app">
    <div>{{number + 1}}</div>
    <div v-bind:id="'list-' + id"></div>
    <div>{{message.split('').reverse().join('')}}</div>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            number: 2,
            id: 'li',
            message: 'hello,wolrd'
        }
    })
</script>

Each template can only contain one JavaScript expression. If there are multiple expressions, they will not work.

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

<!-- Flow control will not work, use ternary expressions instead -->
{{ if (ok) { return message } }}

2. Directives#

Arguments

Some directives can accept an "argument" indicated by a colon after the directive name. For example, the v-bind directive can be used to dynamically update HTML attributes:

<div id="app">
    <a v-bind:href="url">Baidu</a>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            url: 'https://www.baidu.com'
        }
    })
</script>

Here, href is the argument that tells the v-bind directive to bind the href attribute of the element to the value of the expression url.

Another example is the v-on directive, which is used to listen to DOM events:

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

Dynamic Arguments

Starting from 2.6.0, you can use JavaScript expressions enclosed in square brackets as a directive's argument.

<!-- Note that there are some constraints on the syntax of the argument expression, as described in the "Constraints on Dynamic Argument Expressions" section below. -->
<a v-bind:[attributeName]="url">...</a>

Here, attributeName will be dynamically evaluated as a JavaScript expression, and the final result will be used as the argument.

For example, if there is an attributeName property in the Vue instance with a value of href, this binding will be equivalent to v-bind:href.

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

Dynamic event names can also be bound to event listeners:

<a v-on:[eventName]="doSomething"> ... </a>

If the value of eventName is click, this binding will be equivalent to v-on:click="doSomething", a mouse click event.

Constraints on the value of dynamic arguments

Dynamic arguments are expected to evaluate to a string. In exceptional cases, the value will be null, which can be explicitly used to remove the binding. Any other non-string value will trigger a warning.

Constraints on Dynamic Argument Expressions

Dynamic argument expressions have some syntax constraints because certain characters, such as spaces and quotes, are invalid in HTML attribute names. For example:

<!-- This will trigger a compilation warning -->
<a v-bind:['foo' + bar]="value"> ... </a>

Therefore, it is best to avoid expressions with spaces and quotes, or use computed properties instead of complex expressions.

When using templates in the DOM (writing templates directly in an HTML file), it is also necessary to avoid using uppercase characters as attribute names, as the browser will force all attribute names to be lowercase in HTML.

Modifiers

Modifiers are special postfixes indicated by a dot, which are used to indicate that a directive should be bound in a special way. For example, the .prevent modifier tells the v-on directive to call event.preventDefault() on the triggered event.

<form v-on:submit.prevent="onSubmit">...</form>

3. Shorthands#

The v- prefix serves as a visual cue for identifying Vue-specific attributes in the template. It is helpful when adding dynamic behavior to existing tags using Vue.js. However, for some frequently used directives, it can be cumbersome to use the v- prefix. At the same time, the v- prefix becomes less important when building single-page applications (SPAs) where Vue manages all templates. Therefore, Vue provides specific shortcuts for the two most commonly used directives, v-bind and v-on.

v-bind

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

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

<!-- Shorthand for dynamic arguments (2.6.0+) -->
<a :[key]="url"> ... </a>

v-on

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

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

<!-- Shorthand for dynamic arguments (2.6.0+) -->
<a @[event]="doSomething"> ... </a>

They may look slightly different from regular HTML, but : and @ are valid characters for attribute names and can be correctly interpreted in all Vue-supported browsers. Moreover, they will not appear in the final rendered markup. The shorthand syntax is completely optional, but as you become more familiar with their purpose, you will be glad to have them.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.