Vue.js front-end development study notes

Table of contents

1. Introduction to Vue.js

1.1 What is Vue.js

1.2 Features and advantages of Vue.js

1.3 Comparison of Vue.js and other front-end frameworks

2. Vue.js basics

2.1 Vue instance

2.2 Template syntax

2.3 Computed properties

2.4 Listener

2.5 Conditional rendering and list rendering

2.6 Event handling

2.7 Form processing

2.8 Component development

3. Vue components

3.1 What are Vue components

3.2 Create components

3.2.1 Global registration

3.2.2 Partial registration

3.3 Using components

3.4 Communication of components

3.4.1 Parent-child component communication

3.4.2 Sibling component communication

3.4.3 Cross-level component communication

3.5 Component life cycle

4. Vue routing

4.1 What is Vue routing

4.2 Install and configure Vue routing

4.2.1 Install Vue Router

4.2.2 Configure routing

4.3 Basic use of routing

4.3.1 Components

4.3.2 Components

4.4 Routing parameters and dynamic routing

4.5 Nested routing

4.6 Navigation Guard

5. Vue state management

5.1 What is Vue state management

5.2 Vuex

5.3 Install and configure Vuex

5.3.1 Install Vuex

5.3.2 Configuring Vuex

5.4 Using Vuex

5.5 Modularity

6. Vue interacts with the backend

6.1 What is Vue interacting with the backend?

6.2 AJAX requests

6.2.1 Install and configure Axios

6.2.2 Using Axios to send requests

6.3 RESTful API

6.3.1 Define RESTful API

6.3.2 Using RESTful API

6.4 WebSocket

6.4.1 Using WebSocket

6.4.2 Install and configure Vue-Socket.io

6.4.3 Using WebSocket in components

7.Vue common problems and solutions

7.1 How to use components in Vue?

7.2 How to perform data binding in Vue?

7.3 How to perform conditional rendering in Vue?

7.4 How to loop through a rendering list in Vue?

7.5 How to handle user input in Vue?

7.6 How to send AJAX request in Vue?


1. Introduction to Vue.js

1.1 What is Vue.js

Vue.js is a lightweight, flexible JavaScript framework for building user interfaces. It adopts the MVVM (Model-View-ViewModel) architectural pattern to associate data models and views through two-way data binding. Vue.js has concise syntax and powerful functions, allowing developers to build interactive front-end applications more efficiently.

1.2 Features and advantages of Vue.js

  • Simple and easy to use: The syntax of Vue.js is concise and clear, and it is easy to get started. Developers can quickly get started and build projects using Vue.js.
  • Two-way data binding: Vue.js adopts a responsive data binding mechanism, so that data changes can be automatically reflected on the view, and user operations can also be automatically updated into the data model.
  • Component-based development: Vue.js splits the application into multiple reusable components, making the code structure clear, highly maintainable, and improving development efficiency.
  • Lightweight and efficient: Vue.js is small in size, fast in loading speed, and has high-performance rendering capabilities to provide a smooth user experience.
  • Rich ecosystem: Vue.js has huge community support, with many plug-ins and tools to choose from. The rich ecosystem allows developers to build applications more quickly.

1.3 Comparison of Vue.js and other front-end frameworks

  • Vue.js vs React: Vue.js and React are both popular front-end frameworks. They both adopt virtual DOM and component-based development methods. Vue.js is simpler and easier to learn and suitable for small and medium-sized projects, while React is more suitable for large projects and complex applications.
  • Vue.js vs Angular: Vue.js and Angular are both popular front-end frameworks, and their design ideas and usage have certain differences. Vue.js is more lightweight and has a lower learning curve, while Angular is more complete and powerful, suitable for large-scale enterprise-level applications. Vue.js is a powerful and easy-to-use front-end framework with wide application and active community support in the field of front-end development. In the following study notes, we will explore various aspects of Vue.js in depth to help you quickly master the usage skills and best practices of Vue.js.

2. Vue.js basics

2.1 Vue instance

A Vue instance is the root instance of a Vue.js application and is created by instantiating a Vue class. When creating a Vue instance, you can pass in an options object to configure the behavior and properties of the instance.

// 创建Vue实例
var vm = new Vue({
  // 选项
  el: '#app', // 指定挂载的元素
  data: { // 数据
    message: 'Hello Vue!'
  },
  methods: { // 方法
    greet: function() {
      alert(this.message);
    }
  }
});

2.2 Template syntax

Vue.js uses HTML-based template syntax to bind data to the DOM. Data can be displayed dynamically in templates through double curly brace interpolation expressions and directives.

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

2.3 Computed properties

A computed property is a special property in a Vue instance that is used to calculate and process data and return a new value. The value of a computed property is cached and recalculated only when the dependent data changes.

var vm = new Vue({
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: function() {
      return this.firstName + ' ' + this.lastName;
    }
  }
});

2.4 Listener

Vue.js provides a way to listen for changes in data and perform corresponding operations when the data changes by using ​watch​properties .

var vm = new Vue({
  data: {
    message: 'Hello Vue!'
  },
  watch: {
    message: function(newValue, oldValue) {
      console.log('message changed from ' + oldValue + ' to ' + newValue);
    }
  }
});

2.5 Conditional rendering and list rendering

Vue.js provides some instructions to implement conditional rendering and list rendering functions. The directive​v-if​ is used to decide whether to render an element based on the value of an expression. ​v-for​The directive is used to traverse an array or object and render the corresponding element.

<div id="app">
  <p v-if="showMessage">{
   
   { message }}</p>
  <ul>
    <li v-for="item in items">{
   
   { item }}</li>
  </ul>
</div>

2.6 Event handling

Vue.js provides ​v-on​directives to listen to DOM events and execute corresponding methods when the events are triggered. The event type can be passed through the directive's parameters, and modifiers can be used to change the behavior of the event.

<div id="app">
  <button v-on:click="greet">Click me</button>
</div>
var vm = new Vue({
  methods: {
    greet: function() {
      alert('Hello Vue!');
    }
  }
});

2.7 Form processing

Vue.js provides some instructions to handle form input and binding. ​​Instructions​v-model​ can implement two-way data binding and associate form inputs with data models.

<div id="app">
  <input v-model="message" type="text">
  <p>{
   
   { message }}</p>
</div>
var vm = new Vue({
  data: {
    message: ''
  }
});

2.8 Component development

Vue.js supports component development, splitting the application into multiple reusable components. Define components through ​Vue.component​the method , and then use custom tags to reference the components in the template.

<div id="app">
  <my-component></my-component>
</div>
Vue.component('my-component', {
  template: '<p>This is my component</p>'
});
var vm = new Vue({
  el: '#app'
});

The above is the content of the basic part of Vue.js, covering topics such as Vue instances, template syntax, calculated properties, listeners, conditional rendering and list rendering, event processing, form processing and component development. These basic knowledge are the basis for learning and using Vue.js, laying a solid foundation for subsequent learning. In the following study notes, we will continue to explore various aspects of Vue.js in depth.

3. Vue components

3.1 What are Vue components

Vue components are a core concept in Vue.js, which can split an application into multiple independent, reusable parts. Components are composed of templates, data, methods, styles, etc. They can be used multiple times and can be nested in other components.

3.2 Create components

There are two ways to create components in Vue: global registration and local registration.

3.2.1 Global registration

Globally registered components can be used anywhere in the application. A component can be registered globally using ​Vue.component​the .

Vue.component('my-component', {
  template: '<p>This is my component</p>'
});

3.2.2 Partial registration

Locally registered components can only be used in specified Vue instances. Components can be registered in ​components​the options .

var vm = new Vue({
  el: '#app',
  components: {
    'my-component': {
      template: '<p>This is my component</p>'
    }
  }
});

3.3 Using components

To use a component, you need to reference the component's tag in the template. You can use custom tags to reference components and pass component property values ​​to the component.

<div id="app">
  <my-component message="Hello Vue!"></my-component>
</div>

3.4 Communication of components

In Vue, communication between components can be achieved through parent-child component communication, sibling component communication and cross-level component communication.

3.4.1 Parent-child component communication

Parent-child component communication is the most common component communication method. The parent component can pass data to the child component in the form of attributes, and the child component can receive the data passed by the parent component through ​props​options .

Vue.component('child-component', {
  props: ['message'],
  template: '<p>{
   
   { message }}</p>'
});
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
});
<div id="app">
  <child-component :message="message"></child-component>
</div>

3.4.2 Sibling component communication

Sibling component communication refers to communication between multiple child components under the same parent component. Communication between sibling components can be achieved ​event bus​through .

var bus = new Vue();
Vue.component('component-a', {
  template: '<button @click="sendMessage">Send Message</button>',
  methods: {
    sendMessage: function() {
      bus.$emit('message', 'Hello from Component A');
    }
  }
});
Vue.component('component-b', {
  data: function() {
    return {
      receivedMessage: ''
    };
  },
  created: function() {
    var self = this;
    bus.$on('message', function(message) {
      self.receivedMessage = message;
    });
  },
  template: '<p>{
   
   { receivedMessage }}</p>'
});
var vm = new Vue({
  el: '#app'
});
<div id="app">
  <component-a></component-a>
  <component-b></component-b>
</div>

3.4.3 Cross-level component communication

Cross-level component communication refers to communication between components that do not have the same parent-child relationship. Communication between cross-level components can be achieved through ​provide​​​and ​​.​inject​

var parentComponent = {
  provide: {
    message: 'Hello from Parent Component'
  },
  template: '<child-component></child-component>'
};
var childComponent = {
  inject: ['message'],
  template: '<p>{
   
   { message }}</p>'
};
var vm = new Vue({
  el: '#app',
  components: {
    'parent-component': parentComponent,
    'child-component': childComponent
  }
});
<div id="app">
  <parent-component></parent-component>
</div>

3.5 Component life cycle

Vue components have a complete life cycle, from creation, mounting, updating to destruction. During the component's life cycle, corresponding operations can be performed through hook functions.

Vue.component('my-component', {
  template: '<p>{
   
   { message }}</p>',
  data: function() {
    return {
      message: 'Hello Vue!'
    };
  },
  created: function() {
    console.log('Component created');
  },
  mounted: function() {
    console.log('Component mounted');
  },
  updated: function() {
    console.log('Component updated');
  },
  destroyed: function() {
    console.log('Component destroyed');
  }
});
var vm = new Vue({
  el: '#app'
});

The above is the content of the Vue component part, covering topics such as component creation, use, communication and life cycle. Mastering the use of Vue components can better carry out component development and improve the maintainability and reusability of code. In the following study notes, we will continue to delve into other advanced features and usage of Vue.js.

4. Vue routing

4.1 What is Vue routing

Vue routing is a plug-in officially recommended by Vue.js for building single-page applications (SPA). It can realize the jumping and switching of front-end pages, so that users can enjoy page switching similar to traditional multi-page applications when browsing the web. It also facilitates data transfer and status management between pages.

4.2 Install and configure Vue routing

To use Vue routing, you first need to introduce the Vue Router library through npm or CDN. Create a routing file in the project and configure the routing in the Vue instance.

4.2.1 Install Vue Router

Install Vue Router via npm:

npm install vue-router

4.2.2 Configure routing

Create a routing file (such as router.js) in the project and configure routing information in the file:

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
  {
    path: '/',
    component: Home
  },
  {
    path: '/about',
    component: About
  }
];
const router = new VueRouter({
  routes
});
export default router;

Introduce the routing file into the Vue instance and configure routing:

import Vue from 'vue';
import App from './App.vue';
import router from './router';
new Vue({
  el: '#app',
  router,
  render: h => h(App)
});

4.3 Basic use of routing

Use Vue routing ​<router-link>​to ​<router-view>​achieve page jumping and rendering through and components.

4.3.1 ​<router-link>​Components

A component​<router-link>​ is a link used for page jumps. It will be rendered into a ​<a>​label , which will trigger a routing jump when clicked.

<router-link to="/about">About</router-link>

4.3.2 ​<router-view>​Components

​​Components​<router-view>​ are used to render component content matched by the current route.

<router-view></router-view>

4.4 Routing parameters and dynamic routing

Route parameters can be defined through placeholders to match URLs that match specific rules. Use in routing configuration ​:​to define parameters.

const routes = [
  {
    path: '/user/:id',
    component: User
  }
];

You can get the value of the routing parameter in the component ​$route.params​through .

export default {
  created() {
    console.log(this.$route.params.id);
  }
}

4.5 Nested routing

Nested routing allows multiple components to be combined together into a nested page structure. Subroutes can be defined via ​children​options .

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      {
        path: '',
        component: UserProfile
      },
      {
        path: 'posts',
        component: UserPosts
      }
    ]
  }
];

Use in the parent component ​<router-view>​to render the content of the child route.

<router-view></router-view>

4.6 Navigation Guard

Navigation guard is a mechanism provided by Vue routing to perform some logic before and after route jumps. Commonly used navigation guards include ​beforeEach​, , ​beforeResolve​and ​afterEach​.

router.beforeEach((to, from, next) => {
  // 在路由跳转前执行的逻辑
  next();
});
router.beforeResolve((to, from, next) => {
  // 在路由跳转前解析完异步组件后执行的逻辑
  next();
});
router.afterEach((to, from) => {
  // 在路由跳转后执行的逻辑
});

The above is the content of the Vue routing part, covering topics such as routing installation and configuration, basic usage, parameter passing, nested routing and navigation guards. Mastering the use of Vue routing can better develop single-page applications and achieve rich page switching effects and interactive experiences. In the following study notes, we will continue to learn more about other features and usage of Vue.js.

5. Vue state management

5.1 What is Vue state management

Vue state management refers to the centralized management and control of application data and status in order to facilitate data sharing between different components and achieve unified management of data. In large applications, as the number and complexity of components increases, state management becomes particularly important. It can help us better organize and maintain the data flow of the application.

5.2 Vuex

Vuex is the library officially recommended by Vue.js for state management. It draws on the design ideas of Flux and Redux, and combines it with Vue's responsive mechanism to provide a concise and efficient way to manage the state of the application. Vuex stores the entire application's state in a single state tree, and defines mutations and actions to modify and retrieve state.

5.3 Install and configure Vuex

To use Vuex, you first need to import the Vuex library through npm or CDN. Create a store folder in the project and create an index.js file in it as the Vuex configuration file.

5.3.1 Install Vuex

Install Vuex via npm:

npm install vuex

5.3.2 Configuring Vuex

Configure Vuex in the store/index.js file:

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment');
      }, 1000);
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
});
export default store;

5.4 Using Vuex

Introduce the store into the Vue instance and configure it:

import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
  el: '#app',
  store,
  render: h => h(App)
});

Use Vuex state and methods in components:

<template>
  <div>
    <p>{
   
   { count }}</p>
    <p>{
   
   { doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count;
    },
    doubleCount() {
      return this.$store.getters.doubleCount;
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment');
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync');
    }
  }
};
</script>

In the above example, we use​$store.state.count​​ to get the value of the state, use​$store.getters.doubleCount​​ to get the value of the calculated attribute, use​$store.commit('increment')​​ to trigger the mutation method, and use​$store.dispatch('incrementAsync')​​ to trigger the action method.

5.5 Modularity

When applications become large and complex, Vuex provides a modular way to organize state. The store can be divided into multiple modules, each module has its own state, mutations, actions and getters.

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
};
const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
};
const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
});

Use modular state and methods in components:

<template>
  <div>
    <p>{
   
   { count }}</p>
    <p>{
   
   { doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.a.count; // 访问模块A的状态
    },
    doubleCount() {
      return this.$store.getters['a/doubleCount']; // 访问模块A的计算属性
    }
  },
  methods: {
    increment() {
      this.$store.commit('a/increment'); // 调用模块A的mutation
    },
    incrementAsync() {
      this.$store.dispatch('a/incrementAsync'); // 调用模块A的action
    }
  }
};
</script>

The above is the content of the Vue state management part, covering Vuex installation and configuration, basic usage, modularization and other topics. Mastering the use of Vuex can better manage and share the status of applications, improve development efficiency and code reusability. In the following study notes, we will continue to learn more about other features and usage of Vue.js.

6. Vue interacts with the backend

6.1 What is Vue interacting with the backend?

When developing web applications, data interaction between the front end and the back end is a very important part. Vue provides a variety of ways to interact with the back-end data, including obtaining data through AJAX requests, using RESTful API to add, delete, modify and query data, etc.

6.2 AJAX requests

AJAX (Asynchronous JavaScript and XML) is a technology for asynchronous data interaction with the backend without refreshing the page. The Axios library can be used in Vue to send AJAX requests.

6.2.1 Install and configure Axios

Install Axios via npm:

npm install axios

Create an api folder in the Vue project and create an index.js file in it as the Axios configuration file. Configure Axios in the api/index.js file:

import axios from 'axios';
const instance = axios.create({
  baseURL: 'http://api.example.com', // 后端API的基础URL
  timeout: 5000 // 请求超时时间
});
export default instance;

6.2.2 Using Axios to send requests

Use Axios in the component to send the request:

import api from '../api';
export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      api.get('/users')
        .then(response => {
          this.users = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};

In the above example, we ​api.get('/users')​send , and then save the returned data ​users​into the component's data property.

6.3 RESTful API

REST (Representational State Transfer) is an architectural style for designing web applications that uses a simple set of rules to define the state and operation of resources. When interacting with the backend for data, you can use the RESTful API to define and manage the addition, deletion, modification, and query of resources.

6.3.1 Define RESTful API

In the design of RESTful API, HTTP methods are generally used to represent different operations, such as GET for obtaining resources, POST for creating resources, PUT for updating resources, and DELETE for deleting resources. For example, we can define a ​/users​RESTful to operate user resources:

  • GET /users: Get all users
  • GET /users/{id}: Get the user with the specified id
  • POST /users: Create users
  • PUT /users/{id}: Update the user with the specified id
  • DELETE /users/{id}: Delete the user with the specified id

6.3.2 Using RESTful API

Use RESTful API in components for data manipulation:

import api from '../api';
export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      api.get('/users')
        .then(response => {
          this.users = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    createUser(user) {
      api.post('/users', user)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    },
    updateUser(id, user) {
      api.put(`/users/${id}`, user)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    },
    deleteUser(id) {
      api.delete(`/users/${id}`)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};

In the above example, we use​api.get('/users')​​ to get all users, use​api.post('/users', user)​​ to create new users, use ​api.put(​​/ users/${id}​, user)​​ to update users with specified id, use ​api.delete(​​/ users/${id } ​)​​​to delete the user with the specified id.

6.4 WebSocket

In addition to AJAX and RESTful APIs, Vue also supports real-time two-way communication with the backend using WebSockets. WebSocket is a protocol for full-duplex communication over a single TCP connection, which enables real-time data push and reception.

6.4.1 Using WebSocket

In a Vue project, you can use the Vue-Socket.io library to easily integrate WebSocket functionality.

6.4.2 Install and configure Vue-Socket.io

Install Vue-Socket.io via npm:

npm install vue-socket.io

Configure Vue-Socket.io in the main.js file:

import Vue from 'vue';
import VueSocketIO from 'vue-socket.io';
Vue.use(new VueSocketIO({
  debug: true,
  connection: 'http://api.example.com' // WebSocket的连接地址
}));

6.4.3 Using WebSocket in components

Use Vue-Socket.io in components for real-time communication:

<template>
  <div>
    <p v-for="message in messages" :key="message.id">{
   
   { message.text }}</p>
    <input v-model="newMessage" type="text">
    <button @click="sendMessage">Send</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      messages: [],
      newMessage: ''
    };
  },
  mounted() {
    this.$socket.on('message', message => {
      this.messages.push(message);
    });
  },
  methods: {
    sendMessage() {
      this.$socket.emit('message', { text: this.newMessage });
      this.newMessage = '';
    }
  }
};
</script>

In the above example, we listen for events from the server ​this.$socket.on('message', message => { ... })​via ​message​, and save the received messages into the component's ​messages​array . ​this.$socket.emit('message', { text: this.newMessage })​Send an event to the server via ​message​, passing an object containing text content.

7.Vue common problems and solutions

7.1 How to use components in Vue?

Using components is one of the core features of Vue. To use components in Vue, you first need to define a component. Global components can be defined using the Vue.component() method, or local components can be defined in the components property of a Vue instance. Then, use the component's name to reference it in the template. For example, here's an example of defining a global component and using it in a template:

// 定义全局组件
Vue.component('my-component', {
  template: '<div>这是我的组件</div>'
})
// 创建Vue实例
new Vue({
  el: '#app',
  template: '<my-component></my-component>'
})

7.2 How to perform data binding in Vue?

Data binding in Vue is implemented through directives. Commonly used instructions include v-model, v-bind and v-on.

  • The v-model directive is used to implement two-way data binding, binding the value of the form element to the data attribute in the Vue instance.
  • The v-bind directive is used to bind data attributes in a Vue instance to attributes of HTML elements.
  • The v-on directive is used to listen to DOM events and execute methods in the Vue instance when triggered. For example, here is an example using v-model, v-bind, and v-on:
<div id="app">
  <input v-model="message"> <!-- 使用v-model实现双向数据绑定 -->
  <p v-bind:title="message">鼠标悬停查看绑定的title</p> <!-- 使用v-bind绑定title特性 -->
  <button v-on:click="showAlert">点击我弹出警示框</button> <!-- 使用v-on绑定click事件 -->
</div>
<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    showAlert: function() {
      alert('Hello World!');
    }
  }
})
</script>

7.3 How to perform conditional rendering in Vue?

In Vue, you can use the v-if and v-show instructions for conditional rendering.

  • The v-if directive dynamically adds or removes elements based on whether an expression is true or false. If the expression is true, the element will be rendered into the DOM; if the expression is false, the element will not be rendered into the DOM.
  • The v-show directive switches the display and hiding of elements based on whether the expression is true or false. If the expression is true, the element is displayed; if the expression is false, the element is hidden but still exists in the DOM. For example, here is an example using v-if and v-show:
<div id="app">
  <p v-if="showMessage">这是通过v-if进行条件渲染的文本</p>
  <p v-show="showMessage">这是通过v-show进行条件渲染的文本</p>
  <button v-on:click="toggleMessage">点击切换文本的显示和隐藏</button>
</div>
<script>
new Vue({
  el: '#app',
  data: {
    showMessage: true
  },
  methods: {
    toggleMessage: function() {
      this.showMessage = !this.showMessage;
    }
  }
})
</script>

7.4 How to loop through a rendering list in Vue?

In Vue, you can use the v-for directive to perform loop rendering. The v-for directive can be bound to an array or object, and then render in a loop based on the contents of the array or object. For example, here is an example using v-for:

<div id="app">
  <ul>
    <li v-for="item in items">{
   
   { item }}</li>
  </ul>
</div>
<script>
new Vue({
  el: '#app',
  data: {
    items: ['Item 1', 'Item 2', 'Item 3']
  }
})
</script>

7.5 How to handle user input in Vue?

In Vue, you can use the v-on directive to listen for user input events, and then execute methods in the Vue instance for processing. For example, here is an example of using v-on to handle user input:

<div id="app">
  <input v-model="message" v-on:input="handleChange">
  <p>{
   
   { message }}</p>
</div>
<script>
new Vue({
  el: '#app',
  data: {
    message: ''
  },
  methods: {
    handleChange: function() {
      console.log(this.message);
    }
  }
})
</script>

In the above example, the v-model directive is used to implement two-way data binding, and the value of the input box is automatically synchronized to the message attribute in the Vue instance. At the same time, use the v-on instruction to monitor the input event. When the value of the input box changes, the handleChange method will be triggered to print out the value of the input box.

7.6 How to send AJAX request in Vue?

In Vue, you can use Vue's $http plug-in or a third-party AJAX library (such as axios) to send AJAX requests. When using Vue's $http plug-in, you need to install and import the vue-resource library first. Then, in the Vue instance, you can use this.$http object to send AJAX requests. For example, here's an example of sending an AJAX request using Vue's $http plugin:

<div id="app">
  <button v-on:click="getData">点击发送AJAX请求</button>
  <p>{
   
   { responseData }}</p>
</div>
<script>
new Vue({
  el: '#app',
  data: {
    responseData: ''
  },
  methods: {
    getData: function() {
      this.$http.get('/api/data')
        .then(function(response) {
          this.responseData = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
})
</script>

In the above example, clicking the button will trigger the getData method, sending a GET request to the '/api/data' interface. Then, use Promise's then method to handle the callback when the request is successful, and assign the returned data to the responseData attribute. If an error occurs in the request, use the catch method to handle the error.

Guess you like

Origin blog.csdn.net/q7w8e9r4/article/details/132898831