vue2 skill tree (4) – interpolation, dynamic parameters, instruction modifiers, calculated properties, listeners

Directory

  • Detailed explanation of Vue 2 interpolation
    • text interpolation
    • Raw HTML
    • expression
    • filter
    • Computed properties
    • data binding
  • Dynamic parameters, modifiers and abbreviations for Vue 2 directives
    • dynamic parameters
    • modifier
      • `v-on` modifier
      • `v-bind` modifier
      • `v-model` modifier
    • abbreviation
  • Detailed explanation of Vue 2 computed properties and listeners
    • Computed Properties
    • Watchers

Like, your approval is the motivation for my creation!

Collection, your favor is the direction of my efforts!

Comments, your opinions are the wealth of my progress!

Detailed explanation of Vue 2 interpolation

Vue.js 2 provides a powerful template syntax that allows you to insert dynamic data into HTML templates. This part is often called interpolation. Interpolation is the core of Vue template syntax, used to bind data to the DOM to achieve dynamic rendering. The following is a detailed introduction to the interpolation part of Vue 2 template syntax.

Text interpolation

Text interpolation is the most common interpolation method in Vue 2. It uses double curly braces {{ }} to bind data to the template.

<p>{<!-- -->{ message }}</p>

In this example, message is a data attribute that will be dynamically rendered in the template.

Original HTML

If you need to render raw HTML code instead of plain text, you can use the v-html directive.

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

In this example, the rawHtml data attribute contains HTML code, which is parsed and rendered into a DOM element.

Expression

In interpolation, you can also use JavaScript expressions to manipulate the data. Expressions are used within double curly braces and Vue will interpret them as JavaScript code at compile time.

<p>{<!-- -->{ message.toUpperCase() }}</p>

In this example, the toUpperCase() method converts the value of the message data attribute to uppercase letters.

Filter

Vue 2 allows you to use filters to format data output. Filters can be used in interpolation to process the data before displaying it.

<p>{<!-- -->{ message | capitalize }}</p>
Vue.filter('capitalize', function(value) {<!-- -->
  if (!value) return '';
  value = value.toString();
  return value.charAt(0).toUpperCase() + value.slice(1);
});

In this example, the capitalize filter is used to capitalize the value of the message data attribute.

Computed properties

Computed properties allow you to use calculated property values in templates instead of using raw data properties directly. Computed properties are defined within a Vue instance and automatically update based on their dependent values.

<p>{<!-- -->{ reversedMessage }}</p>
new Vue({<!-- -->
  data: {<!-- -->
    message: 'Hello Vue!'
  },
  computed: {<!-- -->
    reversedMessage() {<!-- -->
      return this.message.split('').reverse().join('');
    }
  }
});

In this example, the reversedMessage computed property is used to display the reversed version of the message data property in the template.

Data binding

The interpolation part of Vue 2 provides a flexible data binding method, allowing you to bind data directly to the template to achieve dynamic rendering and interactivity. Whether displaying plain text, rendering HTML, processing expressions, or using filters, Vue’s interpolation capabilities can meet various rendering needs. This makes Vue a powerful front-end framework for building dynamic and responsive user interfaces.

Vue.js 2’s directives are feature-rich, including dynamic parameters, modifiers, and abbreviations, making them extremely flexible and powerful. The following is a detailed introduction to the dynamic parameters, modifiers and abbreviations of Vue 2 directives.

Dynamic parameters, modifiers and abbreviations of Vue 2 directives

Dynamic parameters

Vue 2 allows you to use dynamic parameters to apply directives to different DOM elements or attributes. Dynamic parameters are JavaScript expressions wrapped in square brackets [] and are used to dynamically set the target of the instruction.

<div v-bind:[attributeName]="value"></div>

In this example, attributeName is a dynamic parameter, and its value will dynamically determine the attribute to be bound.

Modifier

Modifiers are additional options in the form of dots . added after a directive to modify the behavior of the directive. Vue 2 provides a variety of modifiers for different directives.

v-on modifier

  • .stop: Stop event bubbling.
  • .prevent: Prevent the default event.
  • .capture: Event listening will be performed during the capture phase.
  • .self: Fires the handler only on the element that triggered the event.
  • .once: Triggered only once.
  • .passive: Indicates that the event handler will never call preventDefault().
<button v-on:click.stop="doThis"></button>

v-bind modifier

  • .prop: Bind to DOM properties instead of attributes.
  • .camel: CamelCase binding to DOM properties.
<input v-bind:value.prop="message">

v-model modifier

  • .lazy: Replaces the default input event with the change event.
  • .number: Convert the input value to numeric type.
  • .trim: Automatically filter the leading and trailing spaces of the input.
<input v-model.lazy="message">

Abbreviation

Vue 2 provides abbreviations for some commonly used directives to reduce redundancy in templates. Here are some common command abbreviations:

  • v-bind Abbreviation: Use : to represent it, such as :src="url".
  • v-on Abbreviation: Use @ to represent it, such as @click="doSomething".

These abbreviations make templates more concise and readable, while keeping the code readable and maintainable.

Dynamic parameters, modifiers, and abbreviations are part of the Vue 2 directive feature and they make Vue templates more powerful and flexible. By using these features, you can better control the behavior and properties of DOM elements to meet various needs.

Detailed explanation of Vue 2 computed properties and listeners

Vue.js 2 provides two mechanisms, Computed Properties and Watchers, for processing and responding to data changes. These mechanisms allow you to declaratively define data derivation, responses, and side effects. The following is a detailed introduction to Vue 2 computed properties and listeners in many aspects.

Computed Properties

Computed properties are properties calculated based on the data properties of the Vue instance. They depend on other properties and are only recalculated when the dependent properties change. Computed properties have the following characteristics:

  1. Declaration method: Declare computed properties in the computed option of the Vue instance.

    new Vue({<!-- -->
      data: {<!-- -->
        message: 'Hello, Vue!',
      },
      computed: {<!-- -->
        reversedMessage: function() {<!-- -->
          return this.message.split('').reverse().join('');
        },
      },
    });
    
  2. Caching: Computed properties are lazy and will only be recalculated when related dependencies change. When accessing calculated properties multiple times, Vue will cache the calculation results and will not repeat calculations.

  3. Responsiveness: Computed properties are responsive. When the dependent data properties change, the calculated properties will automatically recalculate and update the related views.

  4. Getter and setter: Computed properties have a getter function for getting the property value, and a setter function for modifying the property value.

    computed: {<!-- -->
      fullName: {<!-- -->
        get: function() {<!-- -->
          return this.firstName + ' ' + this.lastName;
        },
        set: function(value) {<!-- -->
          var names = value.split(' ');
          this.firstName = names[0];
          this.lastName = names[1];
        },
      },
    }
    

Computed properties are often used to encapsulate complex logic as properties for use in templates. They help make templates concise and readable, and improve code maintainability.

Watchers

Listeners allow you to execute custom logic when data changes. Unlike computed properties, listeners do not return a new property value, but instead perform some side-effect operations. Listeners have the following characteristics:

  1. Declaration method: Declare the listener in the watch option of the Vue instance.

    new Vue({<!-- -->
      data: {<!-- -->
        message: 'Hello, Vue!',
      },
      watch: {<!-- -->
        message: function(newValue, oldValue) {<!-- -->
          console.log('Message changed from ' + oldValue + ' to ' + newValue);
        },
      },
    });
    
  2. Listening properties: A listener can listen for changes in one or more data properties.

    watch: {<!-- -->
      'person.age': function(newValue, oldValue) {<!-- -->
        console.log('Age changed from ' + oldValue + ' to ' + newValue);
      },
    }
    
  3. Asynchronous operations: Listeners can perform asynchronous operations, such as sending HTTP requests or triggering animations.

    watch: {<!-- -->
      message: {<!-- -->
        handler: 'doAsyncOperation',
        deep: true,
      },
    }
    
  4. Immediate option: You can use the immediate option to execute the listener’s callback function immediately.

    watch: {<!-- -->
      message: {<!-- -->
        handler: 'doSomething',
        immediate: true,
      },
    }
    

Listeners are usually used to handle asynchronous or side-effect operations, such as data persistence, API calls, route navigation, etc. They give you more flexibility to respond to changes in your data and perform appropriate actions.

In actual applications, you can choose to use calculated properties or listeners, or both at the same time, depending on your needs. Computed properties are typically used to handle derived properties based on data, while listeners are used to handle side-effect operations related to data changes. These two mechanisms together build a powerful data response system, making Vue a flexible and efficient front-end framework.