vue official api tutorial: https://cn.vuejs.org/v2/guide/
vue official api document: https://cn.vuejs.org/v2/api/#watch
1, Download the vue special development tool HbuilderX (you can also use other)
Just download and install
HbuilderX Download: https://www.dcloud.io/hbuilderx.html
2, The first example of vue
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{ message }} </div> <body> <script> var vm = new Vue({ // Binding element with id = app el: "#app", // Defining data data: { message : "vue The first example of" } }) </script> </body> </html>
3, v-instruction
v-command function list
v-text display text v-html display HTML v-show element hide / show v-if logic judges and executes corresponding code block v-else logic judges and executes corresponding code blocks v-else-if logic judges and executes corresponding code block v-for loop data data v-on event v-bind assignment (any attribute) v-model data bidirectional binding v-slot slot v-pre skips the compilation of this element and its children V-clock flicker problem handling (element loading order may cause the page to display the unrerendered data) v-once renders elements and components only once
v-text
1. v-text will be output as text
2. v-text will output complete html data as text
3. v-text will output complete script data in the form of text
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <!-- Use v-text instructions --> <span v-text="message"></span><br /> <!-- v-text Will output complete text html data --> <span v-text="msg_html"></span><br /> <!-- v-text Will output complete text script data --> <span v-text="msg_script"></span><br /> </div> <script> var vm = new Vue({ el: "#app", data: { message: "v-text Instruction, output in text mode", msg_html: "<h1>I am html text</h1>", msg_script: "\<script\>alert(1)\</script\>", } }) </script>
Output result
v-html
1. v-html will output normal text information
2. v-html will output HTML text in the way of HTML tags
3. v-html will block script output
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <!-- Use v-html instructions --> <span v-html="message"></span><br /> <!-- v-html Will have html Mode output of html text --> <span v-html="ms_html"></span><br /> <!-- v-html Will shield script Output --> <span v-html="msg_script"></span><br /> </div> <script> var vm = new Vue({ el: "#app", data: { message: "v-html Instruction, will have html Mode output of", ms_html: "<h1>I am html text</h1>", msg_script: "\<script\>alert(1)\</script\>", } }) </script>
Output result
v-show
v-show=true adds the style = "display: none;" attribute directly to the element
v-show=false remove the style = "display: none;" attribute
v-show is a hidden code block, invisible to users, and still exists in html
Note: if a value already exists, set the value to the current value and the result is reversed
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <!-- v-show=true Add elements directly style="display: none;" attribute v-show=false remove style="display: none;" attribute --> <div v-show="isshow1 "> isshow1=true display </div> <div v-show="isshow2"> isshow2=false No display </div> <!-- If the value already exists, set the value to the current value. The result is reversed. The current value isshow1 =true --> <div v-show="isshow1 === true"> isshow1 =true ,Direct setting isshow1 =true (Display), direct settings isshow1 =false (Not shown) </div> <!-- If the value already exists, set the value to the current value. The result is reversed. The current value isshow2 =false --> <div v-show="isshow2 === false"> isshow2 =false,Direct setting isshow2 =false (Display), direct settings isshow2 =true (Not shown) </div> </div> <script> var vm = new Vue({ el: "#app", data: { isshow1: true, isshow2: false, } }) </script>
Output result
v-if
Enter code block with v-if=true
v-if=false do not enter code block
v-if is to remove the code block directly from html. v-if=false will provide a placeholder on the page, which will be found when v-if=true
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <!-- v-if=false A placeholder will be provided on the page when v-if=true This placeholder will be found when --> <span v-if="is_exist1"> v-if=true display</span> <span v-if="is_exist2"> v-if=false No display </span> </div> <script> var vm = new Vue({ el: "#app", data: { is_exist1: true, is_exist2: false, } }) </script>
Output result
v-else-if || v-else
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> num1= {{num1}} <div>=============v-else================</div> <div v-if="num1 > 0.5"> Random number 0.5-1.0 </div> <div v-else> Random number 0.0-0.5 </div> <br /> <div>=============v-else-if================</div> num2= {{num2}} <div v-if="num2 > 0.3 && num2 <= 0.5"> Random number 0.3--0.5 </div> <div v-else-if="num2 > 0.5 && num2 <= 0.7"> Random number 0.5--0.7 </div> <div v-else-if="num2 > 0.7"> Random number 0.7--1.0 </div> <div v-else> Random number 0.0--0.3 </div> </div> <script> var vm = new Vue({ el: "#app", data: { num1: Math.random(), num2: Math.random(), } }) </script>
Output result
v-for (traversal array, object, Set, Map)
Expected: array | object | number | string | Iterable (new in 2.6)
usage <div v-for="item in items"> {{ item.text }} </div> //You can also specify aliases (or keys for objects) for array indexes: <div v-for="(item, index) in items"></div> <div v-for="(val, key) in object"></div> <div v-for="(val, name, index) in object"></div>
Test case code
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> Traversing array <ui> <li v-for="(item, index) in arr"> Indexes-{{index}} ---- {{item}} </li> </ui> <hr /> Traversing objects <ui> <li v-for="(val, key,index) in obj"> Indexes-{{index}} ---- {{key}} = {{val}} </li> </ui> <hr /> ergodic set <ui> <li v-for="(val,index) in set"> Indexes-{{index}} ---- {{val}} </li> </ui> <hr /> ergodic map <ui> <li v-for="(item,index) in map"> Indexes-{{index}} ---- {{item}} ---- value={{item[1]}} </li> </ui> <hr /> </div> <script> //set data var set = new Set(); set.add("set1"); set.add("set2"); //map data var map = new Map(); map.set("id",1); map.set("name","wangsong"); map.set("age","24"); var vm = new Vue({ el: "#app", data: { arr: [1, 2, 3, 4], //array obj: { "id": 1, "name": "wangsong", "age": 24 }, set: set, map: map, //map can be abbreviated } }) </script>
Effect display
v-on (define methods)
1. Event modify data directly
2. Event shorthand v-on: click -- > @ Click
3. Event name passed in by variable method
4. Define method handling event logic
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{message}} <!-- 1,Click to modify directly message parameter --> <button v-on:click="message='world'"> Click value change--world</button> <!-- 2,Abbreviation --> <button @click="message='hello'"> Click value change--hello</button> <!-- 3,Event name passed in by variable method --> <button @[event]="message='Hello'"> Click value change--Hello!</button> <!-- 4,Click to execute logical processing method methods.plus Method --> <button @click="plus(1,'wangsong')"> click</button> </div> <script> var vm = new Vue({ el: "#app", data: { message: "hello", event: "click", //3 }, //Definition method methods: { // 4. Click event processing logic plus: function(id, name) { this.message = "I was clicked id=" + id + " ,name=" + name; } } }) </script>
Effect display
v-bind
assignment
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <!-- Use v-bind assignment --> <input v-bind:value="message"/> <br /> <!-- Abbreviation --> <input :value="message"/> </div> <script> var vm = new Vue({ el: "#app", data: { message: "hello", }, }) </script>
Modify display
v-model
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{message}} <hr /> <!-- Use v-bind assignment --> <input v-bind:value="message"/> <hr /> <!-- Data is bound in both directions. Once this value changes, all data that references this value will change --> <input v-model:value="message"/> </div> <script> var vm = new Vue({ el: "#app", data: { message: "hello", }, }) </script>
Effect display
v-slot
v-pre
v-cloak
v-once
4, Life cycle
Example of official document life cycle: https://cn.vuejs.org/v2/guide/instance.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%BE%E7%A4%BA
1. Life cycle flowchart (official)
2. Lifecycle code sample reference
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{text}} </div> <script> Vue.component('app', { template: '<h3>Life cycle example</h3>', // After instance initialization beforeCreate: function() { console.log("beforeCreate=Instance initialization") }, // Called immediately after the instance is created, created: function() { console.log("created=Instance creation complete") }, // Called before mount begins: the first time the associated render function is called. beforeMount: function() { console.log("beforeMount=Mount start") }, // After the instance is mounted, it is called. mounted: function() { console.log("mounted=Instance already mounted") }, // Called on data update beforeUpdate: function() { console.log("beforeUpdate=Data updating") }, // Called when DOM is updated updated: function() { console.log("updated=DOM To update") }, // Called when activated by a keep alive cached component activated: function() { console.log("activated= keep-alive Cache activation") }, // Called when a component cached by keep alive is deactivated. deactivated: function() { console.log("deactivated= = keep-alive Cache disable") }, // Call before instance destruction beforeDestroy: function() { console.log("beforeDestro= Before instance destruction") }, // Call after instance destruction destroyed: function() { console.log("destroyed= Instance destroyed") }, // Called when an error from a descendant component is caught. The hook receives three parameters: the error object, the instance of the component where the error occurred, and a string containing the source information of the error. This hook can return false to prevent the error from continuing to propagate upward. errorCaptured: function() { console.console.log("errorCaptured= exception occurred") }, }); var vm = new Vue({ // Template defined, El will be invalid el: "#app", data: { text: "life cycle", }, // template will replace the html content bound by el. You can directly define or load Vue.component template: '<app/>', })
5, Component (template)
A string template is used as the identity of the Vue instance. The template will replace the attached element. The contents of the mounted elements are ignored unless the contents of the template have a distribution slot.
If the value starts with #, it is used as a selector and the innerHTML of the matching element is used as the template. A common technique is to include templates with < script type = "x-template" >.
1. Global components
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <body> <div id="app"> {{text}} </div> <script type="text/javascript"> /** * html string of global component */ var son_html = "<div style='background-color: violet;height: 40px;width: 80%;margin-top: 28%;'> "+ " I'm a global subcomponent | news | Friends list | dynamic | Personal Center " + " </div>"; /** * Global component, available anywhere (must be loaded first) */ Vue.component('son', { template: son_html }); /** * A string template is used as the identity of the Vue instance. The template will replace the attached element. The contents of the mounted elements are ignored unless the contents of the template have a distribution slot. * *If the value starts with #, it is used as a selector and the innerHTML of the matching element is used as the template. A common technique is to include templates with < script type = "x-template" >. */ var vm = new Vue({ el: "#app", data: { text: "Template" }, // If template is defined, the html content bound by el will be replaced template: "<div style='background-color: salmon;height: 500px;'>" + "<h1>I am the main component</h1>" + "<son>" + //Slot, introduce various templates (such as upper menu, lower menu, left menu, page) "</div>" }) </script> </body> </html>
Display effect
2. Stand alone components
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <body> <div id="app"> {{text}} </div> <script type="text/javascript" style="width: ;"> /** * html string of component */ var sp_son_html = "<div style='background-color: violet;height: 200px;width: 200px;'> "+ " I am a stand-alone subcomponent" + " </div>"; var vm = new Vue({ el: "#app", data: { text: "Template" }, // If template is defined, the html content bound by el will be replaced template: "<div style='background-color: salmon;height: 500px;'>" + "I am the main component" + "<sp_son>" + //Slot, introduce various templates (such as upper menu, lower menu, left menu, page) "</div>" , //Subcomponent of the current Vue sample, not available elsewhere components: { 'sp_son':{ template: sp_son_html } } }) </script> </body> </html>
Display effect
6, Data monitoring operation
1. v-model + watch data monitoring
Shallow data (watch cannot directly listen to deep data, such as json nested data)
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{num}} <input type="text" v-model:value="num" /> </div> <body> <script> var vm = new Vue({ el: "#app", data: { num: 1, message : "vue The first example of" }, watch:{ //newNum = new value, old value num:function(newNum, oldNum){ console.log(newNum,oldNum); } } }) </script>
Effect display
Deep data
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> {{obj.name}} <input type="text" v-model:value="obj.name" /> </div> <body> <script> var vm = new Vue({ el: "#app", data: { obj:{name:"wangsong"} }, watch:{ obj:{ deep:true, //Deep monitoring handler:function(){ console.log("The data has been modified"); } } } }) </script>
Effect display
2. v-model bidirectional binding, dynamic data calculation
Analog a + B = C
Both a and b use two-way data binding
c. dynamic calculation results by method
<!-- Development environment version with helpful command line warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <input type="number" v-model:value="a" /> x <input type="number" v-model:value="b" /> = {{calc}} </div> <body> <script> var vm = new Vue({ el: "#app", data: { a: 0, b: 0, }, computed: { calc: function() { return parseInt(this.a) * parseInt(this.b); } } }) </script>
Effect display, input numbers to dynamically calculate results
3. Data driven principle (Object.defineProperty)
For reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Monitor the modification and call of name attribute in data to realize data operation
<script> var data ={}; Object.defineProperty(data, "name", { set: function(newV) { console.log("Someone gave name Assignment is made.-"+newV) }, get: function() { console.log("Someone got it name value") return "Test return" } }) </script>