1. Vue lifecycle functions
Each Vue instance goes through a series of initialization procedures before being created. For example, an instance needs to configure a Data Observer, compile the template, mount the instance to the DOM, and then update the DOM as the data changes. During this process, the instance also calls lifecycle hooks, which gives us the opportunity to perform custom logic
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title>Vue instance lifecycle function </title> <script SRC =".. /.. /vue.js"></script> </head> <body> <div id="app"></div> <script> var vm = new Vue({ el:'#app', data:{ test:'template option' }, template:'<div>{{test}}</div>', BeforeCreate :function () {// Called after instance initialization // data Observer and before event/watcher event configuration. Console. log('beforCreate')}, created:function () {// The instance is called after it has been created. // In this step, the instance has completed the following configuration: Data Observer, property and method operations, and watch/ Event event callbacks. However, the mount phase has not yet started and the $EL attribute is not currently visible. Console. log('created')}, beforeMount:function () {// called beforeMount starts: The related render function is first called console.log('beforeMount') console.log(this.$el); }, mounted:function () {// call el when vm.$el is mounted. // If root mounts an element in the document, vm.$el is also in the document when Mounted is called. console.log('mounted') console.log(this.$el); This. $data.test = 'I changed test' // beforeUpdate updated method}, beforeDestroy:function () {// Called before instance destruction. At this step, the instance is still fully available. Console. log('beforeDestrory')}, destroyed:function () {// called after ue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. Console. log('destroyed')}, beforeUpdate:function () {// Called when data is updated, occurs before the virtual DOM is rerendered and patched. You can further change the state in this hook without triggering additional rerendering. Console. log('boforeUpdate')}, updated:function () {// The virtual DOM is rerendered and patched due to data changes, after which the hook is called. // When this hook is called, the component DOM is updated, so you can now perform DOM-dependent operations. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. console.log('updated') this.$destroy(); // Completely destroy an instance. Clean up its connections to other instances and unbind all its instructions and event listeners. // Triggers hooks for beforeDestroy and destroyed. } }) </script> </body> </html>Copy the code
2. Template syntax
Vue.js uses htML-based template syntax that allows developers to declaratively bind DOM to the data of the underlying Vue instance. All vue.js templates are valid HTML, so they can be parsed by standards-compliant browsers and HTML parsers.Copy the code
On the underlying implementation, Vue compiles templates into virtual DOM rendering functions. Combined with the response system, Vue can intelligently calculate the minimum cost of rerendering components when the application state changes and apply it to DOM operations.
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> /.. /vue.js"></script> </head> <body> <div id="app"> {{name}} <! <div v-text="name"></div> <! - text -- > < div v - HTML = "name" : the title = "title" > < / div > <! - is inserted into the content will be as HTML data binding is ignored -- -- > < div v - text = "age + ', '" > < / div > <! - # filters - > {{MSG | capitalize}} < v - bind: a href = "url" > baidu about < / a > v - bind abbreviation <! <a v-bind:href="url"></a> <! <a :href="url"></a> V-on <a v-on:click="doSomething"></a> <! - abbreviation for -- -- > < a @ click = "doSomething" > < / a > < / div > < script > var app = new Vue ({el: '# app, data: {name:' < h1 > Dell < / h1 > ', title:'this is a title', age:20, msg:'this is a message', url:'https://www.baidu.com/' }, filters: { capitalize: function (value) { if (! value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } } }) console.log(app.$data) </script> </body> </html>Copy the code
3. Calculate properties, methods, listeners
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> Calculate attributes, methods, listener </title> <script SRC =".. /.. /vue.js"></script> </head> <body> <div id="app"> <! Get fullName--> <! -- The first way --> <! --{{ fullName }}--> <! -- The second way --> <! --{{getFullName()}}--> <! - the third way - > {{fullName}} {{age}} < / div > < script > var = new vm Vue ({el: '# app, data: {firstName:' Dell '. LastName :'Lee', age:20, fullName:'Dell Lee'}, // computed:{// fullName:function () {// console.log('fullName computed once ') // return this.firstName+" "+ enclosing the lastName / / / /}}, / / the methods: {/ / / / if not depend on the value of the change, // getFullName:function () {// console.log('getFullName calculated once ') // return this.firstName+" "+this.lastName //} / /}, Watch :{// # Similar to computed firstName:function () {console.log(' I performed firstName') return this.fullName = this.firstName+this.lastName }, LastName :function () {return this.fullname = this.firstname + this.lastname console.log(' I executed lastName')}, } }) </script> </body> </html>Copy the code
4. Calculate the setter and getter for the property
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> Calculate attributes setter and getter</title> <script SRC =".. /.. /vue.js"></script> </head> <body> <div id="app"> {{fullName}} </div> <script> var vm = new Vue({ el:"#app", data:{ firstName:'Dell', lastName:'Lee', }, computed: { fullName: {// # when the value of a dependency changes, Get :function () {return this.firstName + "" + this.lastName}, set:function (value) {var name = value.split(" "); console.log(name); this.firstName = name[0]; this.lastName = name[1]; } } } }) </script> </body> </html>Copy the code
5. Style binding
We can pass v-bind:class an object to dynamically switch classes for example:
:class=”{activated:isactivated}”
The syntax above indicates that the update of Activated will depend on whether the data attribute isActive is true.
Dynamic switching:
<div @click="HandleDivClick" :class="{activated:isactivated}">hello world</div> HandleDivClick:function () { this.isactivated = ! this.isactivated }Copy the code
:class = “[class1,class2,class3……] “Add multiple styles
<div @click="HandleDivClick1" :class="[activated,'defaultClass']">hello world1</div> HandleDivClick1:function () { this.activated = this.activated==='activated'? '':'activated'; }Copy the code
6. Bind inline styles
The v-bind:style object syntax is straightforward — it looks a lot like CSS, but it’s actually a JavaScript object. CSS property names can be camelCase or kebab-case
<div :style="styleObj" @click="HandleDivClick2">my style</div> styleObj:{ color:'black', fontSize:'50px' } HandleDivClick1:function () { this.activated = this.activated==='activated'? '':'activated'; } <div :style="[styleObj,{cursor:'pointer'}]" @click="HandleDivClick2">my style</div> HandleDivClick2:function () { this.styleObj.color = this.styleObj.color==='black'? 'red':'black'; }Copy the code
7. Conditional rendering
V-if is true conditional rendering because it ensures that the conditional block properly destroys and rebuilds event listeners and subcomponents within the conditional block during the switch.
V-if is also lazy: if the condition is false during the initial render, nothing is done — local compilation starts when the condition is true for the first time (compilation is cached).
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> Conditional render </title> <script SRC =".. /.. /vue.js"></script> </head> <div id="app"> <div v-if="show" data-test="v-if">{{message}}</div> <div v-else>Bye</div> <! -- The V-else element must be immediately followed by the V-if or v-show element -- otherwise it cannot be recognized --> <! --#dom exists on the page, display: none; --> <div v-show="show" data-test="v-show">{{message}}</div> <template> <div v-if="charactor === 'a'">This is A</div> <div v-else-if="charactor==='b'">This is B</div> <div v-else>This is others</div> </template> <div V-if =" myInput ==='email'"> email: <input type="text" key="email"> </div> <div v-else> <input type="text" key="username"> </div> </div> <body> <script> var vm = new Vue({ el:"#app", data:{ show:false, message:'hello world', charactor:'a', myinput:'email' } }) </script> </body> </html>Copy the code
In contrast, V-Show is much simpler — elements are always compiled and retained, and simply switched based on CSS.
In general, V-if has a higher switching cost and V-show has a higher initial rendering cost. Therefore, v-show is better if frequent switching is required, and v-if is better if conditions are unlikely to change at run time
Because v-if is an instruction, you need to add it to an element. But what if we want to switch between multiple elements? At this point we can take a
element as a wrapper element and use v-if on it, which will not be included in the final render
8. List rendering
We use the V-for instruction to render from an array of options. The V-for directive requires special syntax in the form of item in items, which is the source data array and item is the alias of the iteration of the array elements
You can also use of instead of in as a separator, since it is the syntax closest to a JavaScript iterator
List traversal:
<div v-for="(item,index) in list" :key="item.id">
{{item.text}}--{{index}}
</div>
list:[
{
id:'asjdflsfsaf',
text:'hello'
},
{
id:'12316581',
text:'dong'
},
{
id:'wefdsadf',
text:'nyyyy'
},
],
Copy the code
Object traversal:
UserInfo:{ username:"boss dong", age:20, school:'ny' } <! - key: a key item: value index: index -- > < div v - for = "(item, the key index) in the UserInfo" > {{item}} - {{key}} - {{index}} < / div >Copy the code
Vue array method: Push pop Shift unshift splice sort reverse
Key data view bidirectional modification:
Changes to list data (e.g. changes to the second item) :
/ / method 1. Splice () / / syntax / / arrayObject splice (index, howmany, item1,... ,itemX) // Parameter description // index required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. // howmany required. Number of items to delete. If set to 0, the project will not be deleted. // item1, ... ItemX is optional. The new item added to the array. Enclosing a list. The splice (1, 1, {id: 'XLJ, text:' new dong '}); This. list=[{id:'asjdflsfsaf', text:'hello'}, {id:'12316581', text:'new dong'}, {id:'wefdsadf', Set (this.list,1,{id:'456789', text:'changed by vue.set '})Copy the code
Object data modification:
//方法1:// this.UserInfo.username = 'new boss';
// 方法2:
Vue.set(this.UserInfo,'username','new boss');
Copy the code
Object adds data:
Method 1. Add a plAC field, // this.UserInfo = {// username:"boss dong", // age:20, // school:'ny', / / place: 'chongqing' / / / /} method 2. Vue. Set method Vue. Set (enclosing the UserInfo, 'place' and 'Beijing')Copy the code
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> List render </title> <script SRC =".. /.. /vue.js"></script> </head> <body> <div id="app"> <div v-for="(item,index) in list" :key="item.id"> {{item. Text}}, {{index}} < / div > < button @ click = "HandleBtnClick" > modify dong < / button > <! --<template v-for="(item,index) in list">--> <! --<div :key="item.id">--> <! --{{item.text}}--{{index}}--> <! --</div>--> <! --<span>{{item.text}}</span>--> <! --</template>--> <! -- Object traversal --> <! - key: a key item: value index: index -- > < div v - for = "(item, the key index) in the UserInfo" > {{item}} - {{key}} - {{index}} < / div > < button @click="ChangInfo"> </button> <button @click="AddInfoPlace"> </button> </div> <script> push pop shift unshift splice sort reverse var vm = new Vue({ el:"#app", data:{ list:[ { id:'asjdflsfsaf', text:'hello' }, { id:'12316581', text:'dong' }, { id:'wefdsadf', text:'nyyyy' }, ], UserInfo:{ username:"boss dong", age:20, school:'ny' } }, Methods: {HandleBtnClick: function () {/ / # modify the second / / method 1. Splice () / / syntax / / arrayObject splice (index, howmany, item1,... ,itemX) // Parameter description // index required. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. // howmany required. Number of items to delete. If set to 0, the project will not be deleted. // item1, ... ItemX is optional. The new item added to the array. / / this. List. Splice (1, 1, {id: 'XLJ, text:' new dong '}); This. list=[{id:'asjdflsfsaf', text:'hello'}, {id:'12316581', text:'new dong'}, {id:'wefdsadf', Text :'nyyyy'},] Set (this.list,1,{id:'456789', text:'changed by vue.set '})}, ChangInfo:function () {// // this.UserInfo.username = 'new boss'; // Method 2: vue.set (this.UserInfo,'username','new boss'); }, AddInfoPlace:function () {// method 1. Add a PLAC field, // this.UserInfo = {// username:"boss dong", // age:20, // school:'ny', / / place: 'chongqing' / / / /} method 2. Vue. Set method Vue. Set (enclosing the UserInfo, 'place' and 'Beijing')}}}) < / script > < / body > < / HTML >Copy the code