[Front-end Series No. 7] Vue: A Progressive JavaScript Framework

     Vue is a JavaScript framework for building user interfaces, which has the following characteristics:

  • Progressive : Vue can flexibly choose the way to use libraries or frameworks according to different usage scenarios, so as to achieve progressive development.
  • Responsive : Vue implements efficient responsive rendering through data binding and virtual DOM technology, allowing data changes to be automatically reflected on the view without manual manipulation of the DOM.
  • Componentization : Vue provides a set of componentized programming models, allowing developers to build complex and easy-to-maintain user interfaces by reusing and combining components.
  • Rich ecology : Vue has a large and active community, providing many excellent plug-ins and tools, such as Vuex, Vue Router, Nuxt.js, etc., which can help developers solve various problems.

        In this article, I will introduce the basic usage of Vue, including how to create a Vue instance, how to use template syntax, how to define and use components, and how to use some core features of Vue.


Table of contents

1. Create a Vue instance

2. Use template syntax

3. Define and use components

4. Use the core features of Vue

V. Summary


1. Create a Vue instance

To use Vue, you first need to create a Vue instance. A Vue instance is an object that represents a Vue application. We can create a Vue instance by means of new Vue(options), where options is an object used to configure various options of the Vue instance. For example:

// 创建一个 Vue 实例
var app = new Vue({
  // 选项
  el: '#app', // 指定挂载点
  data: { // 定义数据
    message: 'Hello, Vue!'
  }
})

In the code above, we created a Vue instance called app and passed in an options object. Among them, the el option specifies which HTML element the instance will be mounted on, here is the element whose id is app. The data option defines the data of the instance, here is a message attribute. We can access or modify this property through app.message.

2. Use template syntax

Vue provides a concise and powerful template syntax that allows us to declaratively bind data and logic in HTML. Template syntax mainly includes the following:

  • Interpolation : We can use double braces { { }} to interpolate dynamic data or expressions. For example:
<div id="app">
  <p>{
   
   { message }}</p>
</div>

This will display the value of message on the page.

  • Directives : We can use the v- prefix to denote directives. Directives are special attributes that add some extra functionality or behavior to an element. For example:
<div id="app">
  <p v-if="show">{
   
   { message }}</p>
</div>

This will determine whether to display the p element according to the value of show.

  • Events : We can use the v-on directive to bind event listeners. For example:
<div id="app">
  <button v-on:click="sayHello">Click Me</button>
</div>

This will call the sayHello method when the button is clicked.

  • Two-way binding : We can use the v-model directive to achieve two-way binding between form elements and data. For example:
<div id="app">
  <input v-model="message">
  <p>{
   
   { message }}</p>
</div>

This will automatically update the value of message when inputting content in the input box, and also display the value of message in the p element.

3. Define and use components

Component is an important concept of Vue, which allows us to encapsulate some reusable UI parts into independent units, thereby improving the maintainability and reusability of the code. We can define a global component by Vue.component(name, options), where name is the name of the component and options is the option object of the component. For example:

// 定义一个名为 hello 的组件
Vue.component('hello', {
  // 组件的选项
  template: '<p>Hello, {
   
   { name }}!</p>', // 组件的模板
  data: function () { // 组件的数据
    return {
      name: 'Vue'
    }
  }
})

In the above code, we define a component called hello, which has a template option to specify the template of the component, here is a p element. It also has a data option, which is used to return the data of the component, here is a name attribute. Note that the component's data must be a function, not an object, this is to ensure that each component instance has its own independent data.

We can use the defined components in the template of any Vue instance, just like using normal HTML elements. For example:

<div id="app">
  <hello></hello>
</div>

This will display Hello, Vue! on the page.

4. Use the core features of Vue

In addition to the basic usage described above, Vue also has some core features that allow us to develop complex applications more efficiently. Here we only briefly introduce some commonly used features, and for more features, please refer to [Official Documents].

  • Computed property : A computed property is a property that performs calculations based on dependent data and caches the results. We can define computed properties with the computed option. For example:
var app = new Vue({
  el: '#app',
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    // 定义一个计算属性 fullName
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

In the above code, we defined a computed property fullName that returns the full name based on firstName and lastName. We can access computed properties like normal properties, for example { { fullName }}. A computed property is automatically updated when the data it depends on changes.

  • Listener : A listener is a method used to listen for data changes and perform corresponding actions. We can define listeners through the watch option. For example:
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello, Vue!'
  },
  watch: {
    // 定义一个侦听器 message
    message: function (newValue, oldValue) {
      console.log('message changed from ' + oldValue + ' to ' + newValue)
    }
  }
})

In the above code, we define a listener message, which will perform corresponding operations when the value of message changes, here is to print out the value before and after the change. Listeners allow us to make more complex or asynchronous responses to data changes.

  • slot

Slots are a mechanism used to implement component content distribution. We can define the slot through the slot tag, and then when using the component, put the content we want to distribute in the component tag. For example:

<!-- 定义一个名为 card 的组件 -->
<template>
  <div class="card">
    <div class="card-header">
      <!-- 定义一个名为 header 的插槽 -->
      <slot name="header"></slot>
    </div>
    <div class="card-body">
      <!-- 定义一个默认的插槽 -->
      <slot></slot>
    </div>
  </div>
</template>

<!-- 使用 card 组件 -->
<card>
  <!-- 分发 header 插槽的内容 -->
  <template v-slot:header>
    <h3>Vue</h3>
  </template>
  <!-- 分发默认插槽的内容 -->
  <p>Vue is a progressive framework for building user interfaces.</p>
</card>

In the above code, we define a component called card, which has two slots: a named slot called header, which is used to display the title of the card; a default anonymous slot, which is used to display the card Content. Then we distribute the content of the slot through the template tag and the v-slot directive when using the card component. In this way, content reuse and customization of components can be realized.

  • contamination

Mix-in is a technique used to achieve component option reuse. We can define a global mixin through Vue.mixin(options), or define a local mixin through the mixins option. A mixin can contain any component options, and when a component uses a mixin, the mixin's options are merged into the component's own options. For example:

// 定义一个全局混入
Vue.mixin({
  // 混入对象的选项
  created: function () {
    // 在组件创建时打印出组件名称
    console.log(this.$options.name)
  }
})

// 定义一个局部混入
var myMixin = {
  // 混入对象的选项
  data: function () {
    return {
      message: 'Hello, mixin!'
    }
  }
}

// 定义一个组件
var app = new Vue({
  el: '#app',
  name: 'app', // 组件名称
  mixins: [myMixin], // 使用局部混入
  data: {
    message: 'Hello, app!'
  }
})

In the code above, we define a global mixin and a local mixin. The global mixin affects all components, it prints out the component name in the created hook function. A local mixin only affects the component that uses it, and it returns a message property in the data function. When the app component uses a local mixin, it merges the options of the mixin object and its own object. If there is an option with the same name, it will be merged or overwritten according to certain rules. For example, here, the data function returns the merged data object, and the message property is overridden by the app component's own value.

  • custom directive

Custom directives are a way to encapsulate low-level operations on elements. We can define a global custom directive through Vue.directive(name, options), or define a local custom directive through the directives option. A custom instruction object can contain some hook functions to perform corresponding operations at different stages. For example:

// 定义一个全局自定义指令
Vue.directive('focus', {
  // 指令对象的钩子函数
  inserted: function (el) {
    // 在元素插入时聚焦元素
    el.focus()
  }
})

// 定义一个局部自定义指令
var myDirective = {
  // 指令对象的钩子函数
  bind: function (el, binding) {
    // 在元素绑定时设置元素的背景色
    el.style.backgroundColor = binding.value
  }
}

// 定义一个组件
var app = new Vue({
  el: '#app',
  directives: {
    color: myDirective // 使用局部自定义指令
  }
})

In the code above, we define a global custom directive and a local custom directive. The global custom directive focus will focus the element when it is inserted. The local custom instruction color will set the background color of the element when the element is bound, and different color effects can be achieved according to the binding value. We can use defined custom directives in any component's template, just like built-in directives. For example:

<div id="app">
  <input v-focus>
  <div v-color="'red'">Red</div>
  <div v-color="'green'">Green</div>
</div>

This will display a focused input field on the page, and two div elements of different colors.

  • filter

A filter is a method used to format or transform data. We can define a global filter through Vue.filter(name, function), or define a local filter through the filters option. The filter function receives data as the first parameter and returns the processed data. We can use filters in interpolation or v-bind expressions, through the pipe character | to represent the filter. For example:

// 定义一个全局过滤器
Vue.filter('capitalize', function (value) {
  // 将数据转换为首字母大写的形式
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

// 定义一个局部过滤器
var myFilter = function (value, suffix) {
  // 将数据添加后缀的形式
  if (!value) return ''
  value = value.toString()
  return value + suffix
}

// 定义一个组件
var app = new Vue({
  el: '#app',
  data: {
    message: 'hello'
  },
  filters: {
    append: myFilter // 使用局部过滤器
  }
})

In the code above, we define a global filter and a local filter. The global filter capitalize converts the data to capitalized form. The partial filter append will add a suffix to the data, and different suffix effects can be achieved depending on the parameters passed in. We can use defined filters in any component's template just like normal functions. For example:

<div id="app">
  <p>{
   
   { message | capitalize }}</p>
  <p>{
   
   { message | append('!') }}</p>
</div>

This displays Hello and hello! on the page.

  •  plug-in

Plugins are a way to add global functionality or features to Vue. We can use a plugin by Vue.use(plugin, options), where plugin is a plugin object or function, and options is an optional configuration object. Plugins can perform the following functions:

Add global methods or properties like Vue.customMethod. In this way, we can call this method or property through Vue.customMethod anywhere. For example:

// 定义一个插件
var myPlugin = {
  // 插件对象的 install 方法
  install: function (Vue, options) {
    // 在 Vue 上添加一个全局方法
    Vue.customMethod = function () {
      console.log('This is a custom method.')
    }
  }
}

// 使用插件
Vue.use(myPlugin)

In the code above, we define a plugin myPlugin which adds a global method customMethod on Vue in the install method. Then we use this plugin via Vue.use(myPlugin). In this way, we can call this method through Vue.customMethod anywhere.

Add global resources such as directives, filters, transitions, etc. This way we can use these resources in any component. For example:

// 定义一个插件
var myPlugin = {
  // 插件对象的 install 方法
  install: function (Vue, options) {
    // 在 Vue 上添加一个全局指令
    Vue.directive('focus', {
      inserted: function (el) {
        el.focus()
      }
    })
  }
}

// 使用插件
Vue.use(myPlugin)

In the code above, we define a plugin myPlugin which adds a global directive focus on Vue in the install method. Then we use this plugin via Vue.use(myPlugin). This way we can focus elements via the v-focus directive in any component.

  • Add instance methods or properties , such as this.$customMethod. In this way, we can call this method or property through this.$customMethod in any component instance. For example:
// 定义一个插件
var myPlugin = {
  // 插件对象的 install 方法
  install: function (Vue, options) {
    // 在 Vue 原型上添加一个实例方法
    Vue.prototype.$customMethod = function () {
      console.log('This is a custom method.')
    }
  }
}

// 使用插件
Vue.use(myPlugin)

In the code above, we define a plugin myPlugin which adds an instance method $customMethod on the Vue prototype in the install method. Then we use this plugin via Vue.use(myPlugin). This way we can call this method through this.$customMethod in any component instance.

Inject component options such as data, methods, computed, etc. This way we can provide some common options for all components. For example:

// 定义一个插件
var myPlugin = {
  // 插件对象的 install 方法
  install: function (Vue, options) {
    // 在所有组件选项中注入 data 和 methods
    Vue.mixin({
      data: function () {
        return {
          message: 'Hello, plugin!'
        }
      },
      methods: {
        sayHello: function () {
          console.log(this.message)
        }
      }
    })
  }
}

// 使用插件
Vue.use(myPlugin)

In the above code, we define a plugin myPlugin which injects data and methods in all component options in install method. Then we use this plugin via Vue.use(myPlugin). This way we can access the message property and sayHello method in any component.

Add custom functionality or features such as routing, state management, internationalization, and more. This way we can provide some advanced functionality or features to our Vue application. For example:

// 定义一个插件
var myPlugin = {
  // 插件对象的 install 方法
  install: function (Vue, options) {
    // 在 Vue 上添加一个自定义功能
    Vue.customFeature = function () {
      // 实现自定义功能的逻辑
    }
  }
}

// 使用插件
Vue.use(myPlugin)

In the above code, we define a plugin myPlugin which adds a custom feature customFeature on Vue in the install method. Then we use this plugin via Vue.use(myPlugin). This way we can use this feature anywhere through Vue.customFeature.

There are many excellent plug-ins in the Vue ecosystem, such as Vuex, Vue Router, Nuxt.js, etc., all of which add global functions or features to Vue through plug-ins. We can install these plugins through package management tools such as npm or yarn, and use them according to the guidelines of official documents. These plug-ins can greatly improve our efficiency and experience in developing Vue applications.

V. Summary

This article introduces the basic usage and advanced features of Vue, including how to create a Vue instance, how to use template syntax, how to define and use components, and how to use slots, mix-ins, custom directives, filters, plug-ins, etc. Vue is a progressive JavaScript framework that allows us to build user interfaces in a concise and powerful way. Vue has many other features and tricks, such as lifecycle hooks, computed property dependencies, dynamic components, scoped slots, functional components, render functions, server-side rendering, etc., which can be found in [Official Documentation] introduction and examples.

Guess you like

Origin blog.csdn.net/TaloyerG/article/details/132389255