Advanced Vue functions

1. Life cycle

Life cycle: describes the complete process of creating, initializing, [running < = > blocking], and finally destroying a component
The process from the creation of Vue instance to the completion of loading and rendering data of web page DOM structure. The main life cycle functions are as follows:

Creation process

breforeCreate(): life cycle hook before instance initialization
Whether instance data can be called: no
Whether DOM objects can be called: existing elements can be accessed, but Vue instance label elements cannot be accessed

created(): the life cycle hook after the instance is created
Whether instance data can be called: Yes
Whether DOM objects can be called: existing elements can be accessed, but Vue instance label elements cannot be accessed

Beforemount(): life cycle hook before DOM structure rendering
Whether instance data can be called: Yes
Whether DOM objects can be called: existing elements can be accessed, but Vue instance label elements cannot be accessed

Mounted (): the life cycle hook after the Don structure is rendered
Whether instance data can be called: Yes
Whether DOM objects can be called: you can access existing elements and Vue instance label elements

Life cycle functions are also often called life cycle hooks
During the process of instance creation, operation and destruction, the lifecycle function automatically executes the call according to the different states of the instance (it is called a hook function by means of events and callback functions)

<div id='app'>	
</div>
<script>
const vm = new Vue({
            el: '#app',
            data: {
              msg:'I am dom data'
            },
            beforeCreate() {
                console.log('beforeCreate Called',this.msg ? this.msg:'Not obtained msg')
            },
            created() {
                console.log('created Called',this.msg ? this.msg:'Not obtained msg')
            },
            beforeMount(){
                console.log('beforeMount Called',this.msg ? this.msg:'Not obtained msg')
            },
            mounted(){
                  console.log('beforeCreate Called',this.msg ? this.msg:'Not obtained msg')
            }
        })
</script>
Operation process

During the operation of Vue instance, it mainly reflects the operations of data synchronous communication and automatic rendering, which mainly includes two life cycles

beforeUpdate() before updating
Updated

beforeUpdate(){
	console.log('beforeUpdate Called')
}
updated(){
	console.log('updated Called')
}
Destruction process

The process of instance destruction is mainly to destroy some components after they are used during component project development, release the occupied system resources, let the system resources load other component service project applications, and improve the maximum utilization of components under the condition of effective resources. It mainly includes two life cycles

beforeDestory(): life cycle before destruction.
destroyed (): life cycle after destruction.

beforeDestory(){
	console.log('beforeDestory Called')
}
destoryed(){
	console.log('destoryed Called')
}

2. Listener

Listener, also known as listener, is a component provided by Vue framework to developers to monitor variable data. Once the monitored variable data changes, the function corresponding to the listener will execute, and the function can carry out business processing / data operation for the changed data
Vue instance: watch, declare listener

<div id='#app'>
	<input type='text' v-model.lazy='msg'>
	<h2>{{msg}}</h2>
</div>
...
<script>
	...
		data:{
			msg: 'I'm monitoring the data'
		},
		watch:{
			msg:{
				handler(newVal,oldVal) {
					alert('The data has changed'+newVal+'<---'+oldVal)
				}
			}
		}
	...
</script>

Note: listeners can be used when the project needs to perform asynchronous or expensive operations when data changes

3. Calculation attribute

Vue provides a component that automatically completes the operation process and obtains the result data according to the known data
Vue instance: computed, which realizes the function of calculating attributes

<div id='#app'>
	<p>Unit Price:{{price}}</p>
	Purchase quantity:<input type='number' v-mode='count'>
	<h2>Subtotal:{{total}}</h2>
</div>
...
<script>
	...
		data:{
			price: '21',
			count:0
		},
		computed:{
			total() {  //In essence, a function can be used as an attribute variable
				return this.price * this.price
			}
		}
	...
</script>

Calculate properties and normal functions
When the data changes, the calculation attribute will automatically call and cache the results. Ordinary functions must be called through the function name to directly execute the code
When the data does not change and the calculation letter will not execute the function code repeatedly (directly using the result data cached in the last operation), the ordinary function will execute the code again (consuming resources)
Compute properties and listeners
Same: when the target data changes, the related functions will be called and executed automatically
The calculation attribute is essentially the result of the function, and the listener only listens to the changes of the data
When it is necessary to perform different business operations or data operations for each data change, it is recommended to use a listener
When changes in data in multiple variables are interrelated, it is recommended to use calculated attributes

4. Filter

A filter is a component that formats the data displayed in the page view
There are two types of filters

Component filter, private filter: can only be used by the current component and instance

...
	fiters:{
		Filter name(Pending data){
			return ...
		}
	}
...

Global filter: can be used by all Vue components / instances

Vue.filter('Filter name',function(){
	return ...
})

Case operation:

<div id="app">
        <h2>Commodity management</h2>
        <table border=1 width=500>
            <tr>
                <td>number</td>
                <td>name</td>
                <td>Unit Price</td>
                <td>Add time</td>
                <td>operation</td>
            </tr>
            <tr v-for="(goods, index) in goodses" :key="goods.id">
                <td>{{index}}</td>
                <td>{{goods.name|formatName}}</td>
                <!-- Private filter -->
                <td>{{ goods.price|formatPrice }}</td>
                <!-- Global filter -->
                <td>{{goods.time|formatTime}}</td>
                <td>
                    <button>add to</button>
                    <button>edit</button>
                </td>
            </tr>
        </table>
    </div>
    <script src="./vue.js"></script>
    <script>
        // 2. Define global filter
        Vue.filter('formatTime', function(dat) {
            var date = new Date(dat)
            return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
        })

        const vm = new Vue({
            el: '#app',
            data: {
                goodses: [
                    {id: 3, name: "Chinese cabbage", price: 8.00, time: Date.now()},
                    {id: 2, name: "Shanghai Qing", price: 12.00, time: Date.now()},
                    {id: 1, name: "Bean curd", price: 9.00, time: Date.now()},
                ]
            },
            filters: {  // 1. Define component filter / private filter
                formatPrice(dat) {
                    return "¥" + dat + "element/Jin"
                },
                formatName(dat) {
                    return "[" + dat + "]"
                }
            }
        })
    </script>

5. Animation transition

Vue framework provides its own unique processing methods for label animation in page view
The animation operation of any label in the page is divided into entry animation and exit animation

Entering the animation: before entering:. v-enter,. v-enter-active, after entering,. v-enter-to
Leave Animation: before leaving,. v-leave-active, after leaving,. v-leave-to

Basic excess effect

Basic transition animation is to realize automatic animation through the six basic types provided by Vue framework

<style>
.v-enter-to,
.v-leave {
	left:0
}
.v-enter-active,
.v-leave-active{
	position: relative,
	transition: all 2s
}
.v-enter,
.v-leave-to{
	left: 200px
}
</style>
<body>
	<div id='#app'>
		<button @click='toggleC'>switch</button>
		<transition appear>
			<h3 v-show='seen'></h3>
		</transition>
	</div>
	...
	<script>
		...
			data:{
				seen:true
			},
			methods:{
				toggleC(){
					this.seen = !this.seen
				}
			}
		...
	</script>
</body>
Custom animation name

In a single HTML web page, there are many tag objects that need animation effect control, and their respective animation styles are not necessarily the same, so they need to be distinguished by the animation with user-defined name

 <style>
        .fade-enter-to,
        .fade-leave{               /* After entering, before leaving  */
            opacity:1;
        }
        .fade-enter-active,
        .fade-leave-active{        /* Leaving: animation, entering  */
           transition: all 2s;
        }
        .fade-enter,
        .fade-leave-to{            /* After leaving, before entering  */
            opacity:0;
        }
 </style>
<body>
    <div id="app">
        <button @click="toggleF">switch</button>
        <transition appear name="fade">
            <h3 v-show="seen2">Transparency transition animation</h3>
        </transition>
    </div>
  ...
    <script>
      		...
            data: {
                seen2: true,
            },
            methods: {
                toggleF() {
                    this.seen2 = !this.seen2
                }
            } 
        })
    </script>
List group animation

Vue uses wrapped labels to realize excessive animation, and only supports single node animation effect. If there are multiple labels inside, the animation effect cannot be realized

//I won't support it
<transition>
	<div><span>1</span> <span>first</span> </div>
    <div><span>2</span> <span>the second</span> </div>
</transition>

Vue provides over animation group implementation for multiple child nodes

<transition>
	<div><span>1</span> <span>first</span> </div>
    <div><span>2</span> <span>the second</span> </div>
</transition>
    <style>
        .top-enter-to,
        .top-leave{             
            top:0;
        }
        .top-enter-active,
        .top-leave-active{      
            position: relative;
           transition: all 2s;
        }
        .top-enter,
        .top-leave-to{         
            top:-500px;
        }
    </style>
<body>
    <div id="app">
        <button @click="toggleT">Animation group toggle display/hide</button>
        <transition-group appear name="top">
            <div v-show="seen3" key="1"><span>1</span><span>first</span></div>
            <div v-show="seen3" key="2"><span>2</span><span>the second</span></div>
        </transition-group>
    </div>
    
    <script src="./vue.js"></script>
    <script>
        const vm = new Vue({
            el: "#app",
            data: {
                seen3: true
            },
            methods: {
                toggleT() {
                    this.seen3 = !this.seen3
                },
            } 
        })
    </script>
</body>
Third party animation library

The animation effect in the project is beneficial to the improvement of user experience. The animation effect independently developed by yourself is often relatively single. At this time, you can end the animation library and complete complex operations, such as Animate.css
Official website: https://animate.style
Note: the animation provided by animation.css can distinguish between entering animation and leaving animation. Confusion will lead to animation failure
For the animation class name provided by animation.css, do not copy the style name by using the official copy style name

  • Official copy name: animate__hinge, this name is invalid when actually used
  • Manual copy name: hinge, actual use: XXXX active class = "animated hinge"
 <transition appear enter-active-class="animated rollIn" leave-active-class="animated hinge">        
     <h1 v-show="seen">animate.css Animation effect</h1>
 </transition>

Vue Foundation
Vue syntax advanced

Tags: Javascript Front-end Vue Vue.js

Posted on Fri, 12 Nov 2021 22:56:47 -0500 by TempleDMDKrazd