Introduction to Vue (leaving you to open the door to Vue)

Table of contents

Preface

1. Introduction to Vue

1. What is Vue

2. Vue application scenarios

3. The role of Vue (importance)

4. What is the MVVM pattern?

5. Open source library URL

2. Getting Started with Vue

1. Basic usage steps

1.1 Introducing Vue.js

1.2 Create Vue instance

1.3 Writing Vue templates

1.4 Data binding and instructions

1.5 Calling Vue methods and life cycle hooks

2. Advantages of Vue

2.1 Native

code

Effect

2.2 Vue writing

Code 1

Effect 1

3. Note:

3. Vue life cycle

1. What is the life cycle of Vue

 2. Vue life cycle diagram

3. Case presentation

code

Effect


Preface

        The previous blogs have all shared knowledge about SpringMVC with you. Today I will bring you something different to share with you. Today I will lead you to open the door of Vue and appreciate what is behind this door. It's wonderful.

1. Introduction to Vue

1. What is Vue

        Vue (pronounced "view") is a popular front-end JavaScript framework . It is used to build user interfaces, especially Single Page Applications (SPA) . Vue's goal is to enable developers to easily build interactive and flexible web applications through simple APIs and responsive data binding.

        Compared with other frameworks (such as Angular and React), Vue is smaller, easier to learn and use. It adopts a componentized approach, allowing developers to split pages into independent and reusable components, thereby improving development efficiency. Vue also provides a powerful command system, conditional rendering, list rendering, event processing and other functions, making it easier for developers to handle user interaction and rendering logic.

        

Official website: https://cn.vuejs.org/

Vue author: You Yuxi/Wuxi, China

  

  Separating front-end and rear-end React

2. Vue application scenarios

Vue application scenarios
Application scenarios illustrate
Single Page Application (SPA) Vue provides tools and technologies for building single-page applications . By using vue-router to implement front-end routing management, you can easily create smooth page switching effects and load corresponding components according to different routes. This makes Vue ideal for developing single-page applications.
Front-end component library Vue's component-based development model makes it very suitable for building front-end component libraries or UI libraries . Developers can encapsulate common UI components as Vue components and provide them to other developers for use, achieving code reuse and simplification while providing unified styles and features.
rapid prototyping Vue provides easy-to-use syntax and development tools , making it possible to quickly create prototypes in a short time. Through Vue's template syntax, data binding and component development , developers can quickly build interactive prototypes, iterate and verify.
multi-page application While Vue is great for single-page applications, it works equally well for multi-page applications. Vue can be easily integrated with existing back-end rendering applications, using Vue only where increased interactivity is needed to enhance the user experience.
mobile application development Vue can be used in conjunction with other mobile development frameworks (such as Cordova, React Native) to build cross-platform mobile applications. Due to Vue's lightweight nature and convenient development method, it is a good choice for building user interfaces in mobile applications.

3. The role of Vue (importance)

  1. Simple and easy to learn : Vue's design concept is simple, easy to learn and easy to use . It provides an intuitive and concise API and clear documentation so that developers can get started quickly. Vue's syntax and concepts are relatively easy to understand, reducing the learning curve and development threshold.

  2. Component development : The core of Vue is the component development model, which can split the page into independent components, each component has its own template, logic and style. This modular development approach improves code maintainability, reusability, and testability.

  3. Responsive data binding : Vue adopts a two-way data binding mechanism. When the data changes, the view will automatically update; conversely, the user's operations will also be synchronized to the data. This responsive data binding reduces the tedious work of manual DOM operations and improves development efficiency.

  4. Ultimate performance : Vue has been optimized in terms of performance. Through virtual DOM and diff algorithm , it effectively reduces unnecessary DOM operations and improves the rendering performance and response performance of the application. Vue also provides features such as asynchronous rendering and lazy updates to further optimize application performance.

  5. Ecosystem and community support : Vue has a large ecosystem and extensive community support, with many third-party libraries and plug-ins to choose from, covering various development needs and scenarios. The richness of these tools and resources provides developers with more choices and extensibility.

4. What is the MVVM pattern?

         MVVM is a software architecture pattern, which is the abbreviation of "Model-View-ViewModel". It is a pattern for developing user interfaces and is commonly used in desktop application and mobile application development.

        In the MVVM pattern, the structure of the application is divided into three main parts :

  1. Model: A model represents an application's data and business logic. It handles the acquisition, storage and processing of data.

  2. View: A view is a visual representation of a user interface. It is responsible for displaying data to the user and receiving input from the user.

  3. ViewModel: View model is the connector between the view and the model. Its main responsibility is to provide data and commands to the view and handle interaction with the view. It binds the data displayed by the view to the data of the model through the data binding mechanism.

        The key idea of ​​MVVM is to extract the application's state and behavior from the view and encapsulate it into the view model. This separation allows views and models to be developed and tested independently, and allows for better logic reuse.

5. Open source library URL

BootCDN - Bootstrap Chinese website open source project free CDN acceleration service

Example

2. Getting Started with Vue

1. Basic usage steps

1.1 Introducing Vue.js

In the HTML file, introduce the Vue.js library into the project by using a CDN link or local download. For example:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

1.2 Create Vue instance

In the JavaScript file, create a Vue instance and configure Vue's behavior and data by passing in the options object. For example:

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
});

1.3 Writing Vue templates

In the HTML file, use Vue's template syntax to write the UI interface, and display the data on the page through data binding. For example:

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

1.4 Data binding and instructions

You can use double curly braces ( { { }}) for data interpolation, you can also use v-bindinstructions to bind data to HTML attributes, and you can also use v-oninstructions to bind event listeners. For example:

<div id="app">
  <p>{
   
   { message }}</p>
  <input v-bind:value="message" v-on:input="message = $event.target.value">
</div>

1.5 Calling Vue methods and life cycle hooks

You can define methods on your Vue instance and v-oncall them using directives, or you can use lifecycle hooks to perform specific operations. For example:

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    changeMessage: function() {
      this.message = 'New message!';
    }
  },
  created: function() {
    console.log('Vue instance created');
  }
});

2. Advantages of Vue

2.1 Native

code
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
		<title>vue入门</title>
	</head>
	<body>
		<div id="app">
			{
   
   {msg}}
			<span id="show">
				
			</span>
			<input id="content"/>
			<button type="button" onclick="tan()">弹屏</button>
		</div>
			
			<script type="text/javascript">
				new Vue({
					el:"#app",
					data(){
						return {msg:'hello vue 你好啊'}
					}
					
				})
				
				function tan(){
					// 获取输入框的值
					var content=$("#content").val();
					// 将输入框的值赋值给span标签
					$("#show").text(content);
				}
				
			</script>
		
	</body>
</html>
Effect

2.2 Vue writing

Code 1
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
		<title>vue入门</title>
	</head>
	<body>
		<div id="app">
			{
   
   {msg}}
			<input v-model="msg" />
		</div>
			
			<script type="text/javascript">
				new Vue({
					el:"#app",
					data(){
						return {msg:'hello vue 你好啊'}
					}
				})
				
				
			</script>
		
	</body>
</html>
Effect 1

This is the data binding effect simulated by using Vue. When our input box inputs something, what is displayed. In our subsequent projects, we can apply it to the project so that when the database changes, the page display will also change. Vice versa.

3. Note:

v-model: two-way binding of data, variables in the boundary, and variables defined in the vue instance.

:value/V-bind:value: Take it out from the defined variable in the vue instance and use it in the boundary.

3. Vue life cycle

1. What is the life cycle of Vue

        The life cycle of Vue refers to the execution order and timing of a series of hook functions provided by Vue during the process of creating, mounting, updating, and destroying Vue instances. The life cycle of Vue can be divided into creation phase, mounting phase, update phase and destruction phase.

  1. Creation stage:

    • beforeCreate: Called before the Vue instance is created, when the data and methods of the instance have not been initialized.
    • created: Called after the Vue instance is created. At this time, the data and methods of the instance have been initialized, but the DOM has not yet been generated.
  2. Mounting phase:

    • beforeMount: Called before the Vue instance is mounted to the DOM. At this time, the compiled template generates a virtual DOM.
    • mounted: Called after the Vue instance is mounted to the DOM. At this time, the template of the instance has been rendered into an actual DOM element.
  3. Update stage:

    • beforeUpdate: Called before the data is updated. At this time, the virtual DOM has been re-rendered but has not yet been applied to the actual DOM.
    • updated: Called after the data is updated and the changes are applied to the DOM. At this time, the DOM has been updated.
  4. Destruction phase:

    • beforeDestroy: Called before the Vue instance is destroyed, when the instance is still fully available.
    • destroyed: Called after the Vue instance is destroyed, when the instance and its related event listeners and timers have been removed.

In short, at each stage, you can perform some specific operations in the corresponding life cycle hook function, such as data initialization, asynchronous request sending and cancellation, DOM operations, etc. Understanding the life cycle of Vue can help you better control and manage the behavior of Vue instances.

 2. Vue life cycle diagram

3. Case presentation

code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
	</head>
	<body>
		<div id="d1">
			<div>number:{
   
   {number}}</div>
			<div>{
   
   {detail()}}</div>
			<input type="text" v-model="number" />
		</div>
		<script>
			var data = {
				number:999,
				msg:null
			};
			var vm = new Vue({
				el:'#d1',
				data:data,
				methods:{
					detail:function(){
						return "使用方法来插值:"+this.msg;
					}
				},
				beforeCreate:function(){
		            console.log('beforeCreate:刚刚new Vue()之后,这个时候,数据还没有挂载呢,只是一个空壳')           
		            console.log(this.msg)//undefined
		            console.log(document.getElementsByClassName("myp")[0])//undefined
		        },
		        created:function(){
		            console.log('created:这个时候已经可以使用到数据,也可以更改数据,在这里更改数据不会触发updated函数')
		            this.msg+='!!!'
		            console.log('在这里可以在渲染前倒数第二次更改数据的机会,不会触发其他的钩子函数,一般可以在这里做初始数据的获取')
		            console.log('接下来开始找实例或者组件对应的模板,编译模板为虚拟dom放入到render函数中准备渲染')
		        },
		        beforeMount:function(){
		            console.log('beforeMount:虚拟dom已经创建完成,马上就要渲染,在这里也可以更改数据,不会触发updated')
		            this.msg+='@@@'
		            console.log('在这里可以在渲染前最后一次更改数据的机会,不会触发其他的钩子函数,一般可以在这里做初始数据的获取')
		            console.log(document.getElementsByClassName("myp")[0])//undefined
		            console.log('接下来开始render,渲染出真实dom')
		        },
		        // render:function(createElement){
		        //     console.log('render')
		        //     return createElement('div','hahaha')
		        // },
		        mounted:function(){ 
		            console.log('mounted:此时,组件已经出现在页面中,数据、真实dom都已经处理好了,事件都已经挂载好了')
		            console.log(document.getElementsByClassName("myp")[0])
		            console.log('可以在这里操作真实dom等事情...')
		
		        //    this.$options.timer = setInterval(function () {
		        //        console.log('setInterval')
		        //         this.msg+='!'  
		        //    }.bind(this),500)
		        },
		        beforeUpdate:function(){
		            //这里不能更改数据,否则会陷入死循环
		            console.log('beforeUpdate:重新渲染之前触发')
		            console.log('然后vue的虚拟dom机制会重新构建虚拟dom与上一次的虚拟dom树利用diff算法进行对比之后重新渲染')         
		        },
		        updated:function(){
		            //这里不能更改数据,否则会陷入死循环
		            console.log('updated:数据已经更改完成,dom也重新render完成')
		        },
		        beforeDestroy:function(){
		            console.log('beforeDestory:销毁前执行($destroy方法被调用的时候就会执行),一般在这里善后:清除计时器、清除非指令绑定的事件等等...')
		            // clearInterval(this.$options.timer)
		        },
		        destroyed:function(){
		            console.log('destroyed:组件的数据绑定、监听...都去掉了,只剩下dom空壳,这里也可以善后')
		        }
			});
		</script>
	</body>
</html>
Effect

Before the input box is adapted

After the input box is adapted

This ends the blog sharing about Vue in this issue. I hope veterans can pay attention and support three times in a row.

 

Guess you like

Origin blog.csdn.net/weixin_74352229/article/details/132922125