Vue learning notes

 

Official documents: https://cn.vuejs.org/v2/guide/

1. Getting to know Vue

Vue is a progressive framework for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from bottom to top. Vue's core library only focuses on view layers, which is not only easy to start, but also easy to integrate with third-party libraries or existing projects. On the other hand, when combined with modern tool chains and various supporting class libraries, Vue can also provide drivers for complex single page applications.

Vue features:

1. Adopt component mode to improve the reuse rate of code and make the code better maintained;

2. Declarative coding allows coders to improve development efficiency without directly operating DOM;

3. Use virtual Dom and excellent Diff algorithm to reuse DOM nodes as much as possible;

 

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>First acquaintance Vue</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8         <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>
 9     </head>
10     <body>
11         <!-- 
12             Front:
13                 1,force refresh  shift+F5
14                 2,Solve web page tags favicon.ico Missing problem, internal server
15                 3,new Vue({Here is the configuration object. Proper nouns should be used, such as el,methods})
16             First acquaintance Vue: 
17                 1.Want Vue To work, you must create one Vue Instance, and a configuration object is to be passed in;
18                 2.app The code in the container still matches html Specification, but mixed with some special Vue Grammar;
19                 3.app The code in the container is called[ Vue Template: the template will be deleted vue The instance resolves to normal html Then mount it into the container;
20                 4.Vue Instances and containers are one-to-one, one-to-one;
21                 5.There is only one in real development Vue Instance, and will be used together with components;
22                 6.{{xxx}}Medium xxx To write js Expression, and xxx It can be read automatically data All attributes in;
23                 7.once data If the data in the page changes, the places where the data is used in the page will also be updated automatically;
24 
25                 Pay attention to distinction: js Expressions and js code(sentence)
26                         1.Expression: an expression will produce a value, which can be placed wherever a value is required:
27                                     (1). a
28                                     (2). a+b
29                                     (3). demo(1)
30                                     (4). x === y ? 'a' : 'b'
31                         2.js code(sentence)
32                                     (1). if(){}
33                                     (2). for(){}
34         -->
35 
36         <!-- Prepare a container -->
37         <div id="app">
38             <h1>Hello,{{name.toUpperCase()}},{{address}}</h1>
39         </div>
40 
41         <script type="text/javascript" >
42             Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
43 
44             //establish Vue example
45             //new It's essential, Vue It is a constructor and cannot be called directly. It must be called through an instance 
46             new Vue({  //Create instance through constructor
47                 el:'#app', //el Used to specify the current Vue Which container does the instance serve? The value is usually css Selector string.
48                 data:{ //data Used to store data for el To use the specified container, we write the value as an object for the time being.
49                     name:'waylon',
50                     address:'Shanghai'
51                 }
52             })
53 
54         </script>
55     </body>
56 </html>

 

 

2. Template syntax

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Template syntax</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- 
11                 Vue There are two types of template syntax:
12                     1.Interpolation syntax:
13                             Function: used to parse the label body content.
14                             Writing method:{{xxx}},xxx yes js Expression, and can be read directly data All properties in.
15                     2.Instruction syntax:
16                             Function: used to resolve tags (including tag attributes, tag body contents, and binding events).....). 
17                             give an example: v-bind:href="xxx" Or abbreviated as :href="xxx",xxx Also write js expression,
18                                      And can be read directly data All properties in.
19                             remarks: Vue There are many instructions in the form of: v-????,Here we just take v-bind for instance.
20 
21          -->
22         <!-- Prepare a container-->
23         <div id="root">
24             <h1>Interpolation syntax</h1>
25             <h3>Hello,{{name}}</h3>
26             <hr/>
27             <h1>Instruction syntax</h1>
28             <!-- add to v-bind:Then you'll=The string on the right js Expression to execute -->
29             <a v-bind:href="school.url.toUpperCase()" x="hello">I'll go{{school.name}}Learning 1</a>
30             <a :href="school.url" :x="hello">I'll go{{school.name}}Learning 2</a>
31         </div>
32     </body>
33 
34     <script type="text/javascript">
35         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
36 
37         new Vue({
38             el:'#root',
39             data:{
40                 hello:'Hee hee',
41                 name:'jack',
42                 school:{
43                     name:'Shang Silicon Valley', //Although the same name, but different levels
44                     url:'http://www.atguigu.com',
45                 }
46             }
47         })
48     </script>
49 </html>

 

3. Data binding

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Data binding</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- 
11             Vue There are two data binding methods in:
12                 1.Unidirectional binding(v-bind): Data can only be from data Flow to page.
13                 2.Bidirectional binding(v-model): Data can not only be obtained from data Flow to and from the page data. 
14             remarks:
15                 1.Bidirectional binding is generally applied to form elements (for example: input,select Etc.)
16                 2.v-model:value Can be abbreviated as v-model,because v-model The default collection is value Value.
17          -->
18         <!-- Prepare a container-->
19         <div id="root">
20             <!-- Common writing: -->
21             <!-- 
22             One way data binding:<input type="text" v-bind:value="name"><br/>
23             Bidirectional data binding:<input type="text" v-model:value="name"><br/> 
24             -->
25 
26             <!-- Abbreviation: -->
27             One way data binding:<input type="text" :value="name"><br/>
28             Bidirectional data binding:<input type="text" v-model="name"><br/>
29 
30             <!-- The following code is wrong because v-model Can only be applied to form class elements (input class elements) -->
31             <!-- <h2 v-model:x="name">How do you do</h2> -->
32         </div>
33     </body>
34 
35     <script type="text/javascript">
36         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
37 
38         new Vue({
39             el:'#root',
40             data:{
41                 name:'Shang Silicon Valley'
42             }
43         })
44     </script>
45 </html>

 

 

4. Two ways of writing el and data

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>el And data Two ways of writing</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- 
11             data And el Two ways of writing
12                 1.el There are two ways to write
13                     (1).new Vue Time configuration el Properties.
14                     (2).Create first Vue Instance, and then pass vm.$mount('#root ') specifies the value of el.
15                     If Vue The instance did not receive a message when instantiating el Option, it is in the "unmounted" state and has no associated DOM Element. can
16                     To use vm.$mount() Manually mount an unmounted instance.
17                 2.data There are two ways to write
18                     (1).Object type
19                     (2).Functional formula
20                     How to choose: you can write either way at present. When you learn components in the future, data You must use a functional expression, otherwise an error will be reported.
21                 3.An important principle:
22                     from Vue Managed functions, such as data(),Never write arrow functions. Once you write arrow functions, this No longer Vue Examples,But Window
23         -->
24         <!-- Prepare a container-->
25         <div id="root">
26             <h1>Hello,{{name}}</h1>
27         </div>
28     </body>
29 
30     <script type="text/javascript">
31         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
32 
33         //el Two ways of writing
34         /*
35         const vm = new Vue({
36             // el:'#root', //The first way to write
37             data:{
38                 name:'Shang Silicon Valley '
39             }
40         })
41         console.log(vm)
42         vm.$mount('#root') //Mount means mount
43         */
44        
45         // data Two ways of writing
46         const vm = new Vue({
47             el:'#root',
48             //data The first way to write: object
49             /* data:{
50                 name:'Shang Silicon Valley '
51             } */
52 
53             //data The second way to write: functional expression
54             data(){        //Namely data:function(){}Abbreviation for
55                 console.log('@@@',this) //Here this yes Vue Instance object
56                 return{
57                     name:'Shang Silicon Valley'
58                 }
59             }
60         })
61     </script>
62 </html>

 

5. MVVM model in Vue

 

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>understand MVVM</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- 
11             MVVM Model
12                 1. M: Model(Model) : data Data in————>js object
13                 2. V: view(View) : Template code————>DOM
14                 3. VM: View model(ViewModel): Vue example
15             Observations:
16                 1.data All the properties in finally appear in vm On me.
17                 2.vm All attributes and Vue prototype[Prototype]All properties on the Vue Templates can be used directly.
18         -->
19         <div id="root">
20             <h1>School Name:{{name}}</h1>
21             <h1>School address:{{address}}</h1>
22             <!-- <h1>Test 1:{{1+1}}</h1>
23             <h1>Test 2:{{$options}}</h1>
24             <h1>Test 3:{{$emit}}</h1>
25             <h1>Test 4:{{_c}}</h1> -->
26         </div>
27     </body>
28 
29     <script type="text/javascript">
30 
31         const vm = new Vue({
32             el:'#root',
33             data:{
34                 name:'Shang Silicon Valley',
35                 address:'Beijing',
36             }
37         })
38         console.log(vm)
39     </script>
40 </html>

 

Vue's instance object vm:

 

The embodiment of MVVM in vue:

 

 

 

6. Data proxy

1. About object Defineproperty method

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>about Object.defineproperty method</title>
 6     </head>
 7     <body>
 8         <script type="text/javascript">
 9             let number = 18
10             let person = {
11                 name:'Zhang San',
12                 sex:'male',
13             }
14             
15             Object.defineProperty(person,'age',{
16                 // value:18,
17                 // enumerable:true, //Controls whether attributes can be enumerated. The default value is false
18                 // writable:true, //Controls whether the attribute can be modified. The default value is false
19                 // configurable:true //Controls whether the attribute can be deleted. The default value is false
20             
21                 //When someone reads person of age Property, get function(getter)Will be called, and the return value is age Value of
22                 get(){
23                     console.log('Someone read age Properties')
24                     return number
25                 },
26             
27                 //When someone modifies person of age Property, set function(setter)Will be called and will receive the modified specific value
28                 set(value){
29                     console.log('Someone modified it age Property and the value is',value)
30                     number = value
31                 }
32                 //getter and setter take person and number The two are related
33             })
34             // console.log(Object.keys(person)) //Extract the property name of the object to form an array
35             
36             console.log(person)
37             52         </script>
53     </body>
54 </html>

2. What is a data broker?

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>What is a data broker</title>
 6     </head>
 7     <body>
 8         
 9         <!-- Data broker: the (reading) of attributes in another object through one object/Write operation -->
10         <script type="text/javascript" >
11             let obj = {x:100}
12             let obj2 = {y:200}
13 
14             Object.defineProperty(obj2,'x',{
15                 get(){
16                     return obj.x
17                 },
18                 set(value){
19                     obj.x = value
20                 }
21             })
22         </script>
23     </body>
24 </html>

 

3. How is the data broker implemented in Vue?

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>Vue Data broker in</title>
 6         <script type="text/javascript" src="js/vue.js"></script>
 7     </head>
 8     <body>
 9         <div id="app">
10             <h1>Personal name:{{name}}</h1>
11             <h1>Individual age:{{age}}</h1>
12         </div>
13         <script type="text/javascript">
14             const vm = new Vue({
15                 el:"#app",
16                 data:{
17                     name:'Sky cyan',
18                     age:18
19                 }
20             })
21         </script>
22     </body>
23 </html>

 

 

In the above code, the data attribute is an object. You can operate the key value pairs in data through the instance object vm, as follows:

 

 

 

 

 

Isn't this the data broker? One object implements (read / write) operations on attributes in another object. This can be seen from the name attribute under the vm instance object. Move the mouse cursor over it to display the Invoke property getter, indicating that the property value should be read through the getter.

 

Both name and age have their own getter s and setter s:

 

 

In fact, there is one under the vm instance object_ Data attribute, which stores the key value pairs in data. You can use vm_ Data to read and write:

 

 

 

 

The name and age under the vm are linked to the vm through the data broker_ The name in the data is associated with the age. If there is no such connection, the {name}} in the template cannot be obtained directly_ The name in data should be {_data.name}}. And_ Data comes from data, so vm can easily operate data by proxy.

Mr. Shang's picture is also very clear:

 

 

To add_ Data hijacking is also implemented in data. When we pass VM When name changes the value, the places where name is used on the page will also be automatically updated in response. This is_ The role of data hijacking in data.

 

Summary:

1. Data broker in Vue:
Proxy the operation (read / write) of the attributes in the data object through the vm object
2. Benefits of data broker in Vue:
More convenient operation of data in data
3. Basic principle:
Through object Defineproperty () adds all the properties in the data object to the vm.
Specify a getter/setter for each property added to the vm.
Operate (read / write) the corresponding properties in data within getter/setter.

 

7. Event handling

 

 

8. Calculation properties

First implement a small case:

 

 

 

The input box has Zhang and San by default, and the full name will be changed after manual input.

1. Implementation case through interpolation syntax

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Name Case_Implementation of interpolation syntax</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             Last name:<input type="text" v-model="firstName"> <br/><br/>
13             Name:<input type="text" v-model="lastName"> <br/><br/>
14             Full name:<span>{{firstName}}-{{lastName}}</span>
15         </div>
16     </body>
17 
18     <script type="text/javascript">
19         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
20 
21         new Vue({
22             el:'#root',
23             data:{
24                 firstName:'Zhang',
25                 lastName:'three'
26             }
27         })
28     </script>
29 </html>

 

2. Implementation of cases through methods

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Name Case_methods realization</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             Last name:<input type="text" v-model="firstName"> <br/><br/>
13             Name:<input type="text" v-model="lastName"> <br/><br/>
14             Full name:<span>{{fullName()}}</span>
15         </div>
16     </body>
17 
18     <script type="text/javascript">
19         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
20 
21         new Vue({
22             el:'#root',
23             data:{
24                 firstName:'Zhang',
25                 lastName:'three'
26             },
27             methods: {
28                 fullName(){
29                     console.log('@---fullName')
30                     return this.firstName + '-' + this.lastName
31                 }
32             },
33         })
34     </script>
35 </html>

Note that {{fullName()}} in line 14 is to add ().

In addition, due to bidirectional data binding, each input will change the attribute value in the data object, which will make the template code re rendered by Vue and the fullName method re called. As follows:

 

3. Implement cases by calculating attributes

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Name Case_Calculation attribute implementation</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
21         <!-- Prepare a container-->
22         <div id="root">
23             Last name:<input type="text" v-model="firstName"> <br/><br/>
24             Name:<input type="text" v-model="lastName"> <br/><br/>
25             Test:<input type="text" v-model="x"> <br/><br/>
26             Full name:<span>{{fullName}}</span> <br/><br/>
27             <!-- Full name:<span>{{fullName}}</span> <br/><br/>
28             Full name:<span>{{fullName}}</span> <br/><br/>
29             Full name:<span>{{fullName}}</span> -->
30         </div>
31     </body>
32 
33     <script type="text/javascript">
34         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
35 
36         const vm = new Vue({
37             el:'#root',
38             data:{
39                 firstName:'Zhang',
40                 lastName:'three',
41                 x:'Hello'
42             },
43             methods: {
44                 demo(){
45                     
46                 }
47             },
48             computed:{
49                 fullName:{
50                     //get What does it do? When someone reads fullName When, get Will be called and the return value will be fullName Value of
51                     //get When will it be called? one.First read fullName Time. two.When the dependent data changes.
52                     get(){
53                         console.log('get Called')
54                         // console.log(this) //After Vue processing, this here is vm
55                         return this.firstName + '-' + this.lastName
56                     },
57                     //set When is it called? When fullName When modified.
58                     set(value){
59                         console.log('set',value)
60                         const arr = value.split('-')
61                         this.firstName = arr[0]
62                         this.lastName = arr[1]
63                     }
64                 }
65             }
66         })
67     </script>
68 </html>

 

 

Summary:

1. Definition: the attribute to be used does not exist. It should be calculated from the existing attribute (such as the attribute in the data object). It is also an attribute under the vm.
2. Principle: the bottom layer uses objcet Getters and setter s provided by the defineproperty method.
3. When does the get function execute?
  (1). It is executed once on the first reading.
  (2). When the dependent data changes, it will be called again.
4. Advantages: compared with the methods implementation, there is an internal caching mechanism (reuse), which is more efficient and convenient for debugging.
5. The calculation attribute will eventually appear on the vm, which can be read and used by direct interpolation method.
6. If the calculation attribute is to be modified, the set function must be written to respond to the modification, and the data that the calculation depends on in the set will be changed.

 

4. Abbreviations for calculated attributes

When only the reading of calculation attributes is considered and no modification is considered, it can be abbreviated as:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Name Case_Calculation attribute implementation</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             Last name:<input type="text" v-model="firstName"> <br/><br/>
13             Name:<input type="text" v-model="lastName"> <br/><br/>
14             Full name:<span>{{fullName}}</span> <br/><br/>
15         </div>
16     </body>
17 
18     <script type="text/javascript">
19         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
20 
21         const vm = new Vue({
22             el:'#root',
23             data:{
24                 firstName:'Zhang',
25                 lastName:'three',
26             },
27             computed:{
28                 //Complete writing
29                 /* fullName:{
30                     get(){
31                         console.log('get Called ')
32                         return this.firstName + '-' + this.lastName
33                     },
34                     set(value){
35                         console.log('set',value)
36                         const arr = value.split('-')
37                         this.firstName = arr[0]
38                         this.lastName = arr[1]
39                     }
40                 } */
41                 //Abbreviation
42                 fullName(){
43                     console.log('get Called')
44                     return this.firstName + '-' + this.lastName
45                 }
46             }
47         })
48     </script>
49 </html>

 

When reading, it is still {{calculated attribute}} and cannot be added ().

 

9. Monitoring properties

Realize weather cases:

 

The default is hot. Click to switch to cool, and then click to switch to hot.

1. Implementation case

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <script type="text/javascript" src="js/vue.js"></script>
 7     </head>
 8     <body>
 9         <div id="app">
10             <h1>The weather is very today{{weather}}</h1>
11             <button type="button" @click="changeWeather">Click me to switch the weather</button>
12             <!-- <button type="button" @click="ishot=!ishot;x Other codes x">Click me to switch the weather</button> -->
13             <!-- <button type="button" @click="window.alert('Click successfully')">Click me to switch the weather</button> -->
14             <!-- When binding events,@xxx='yyy',there yyy You can write some simple sentences and give them to me if they are complex methods -->
15         </div>
16         <script type="text/javascript">
17             const vm = new Vue({
18                 el:'#app',
19                 data:{
20                     ishot:true,
21                     // window  Click in the event window stay vm We can't find it in, so we need to add it here window,Otherwise, an error will be reported
22                 },
23                 methods:{
24                     changeWeather(){
25                         this.ishot = !this.ishot
26                     }
27                 },
28                 computed:{
29                     weather(){
30                         return this.ishot ? 'scorching hot' : 'pleasantly cool'
31                     }
32                 }
33             })
34         </script>
35     </body>
36 </html>

 

 

 

2. Monitor attribute watch

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Weather case_Monitoring properties</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             <h2>It's a fine day today{{info}}</h2>
13             <button @click="changeWeather">Switch weather</button>
14         </div>
15     </body>
16 
17     <script type="text/javascript">
18         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
19         
20         const vm = new Vue({
21             el:'#root',
22             data:{
23                 isHot:true,
24             },
25             computed:{
26                 info(){
27                     return this.isHot ? 'scorching hot' : 'pleasantly cool'
28                 }
29             },
30             methods: {
31                 changeWeather(){
32                     this.isHot = !this.isHot
33                 }
34             },
35             /* watch:{
36                 isHot:{
37                     immediate:true, //Let the handler call during initialization
38                     //handler When will it be called? When isHot changes.
39                     handler(newValue,oldValue){
40                         console.log('isHot Modified '', newValue,oldValue)
41                     }
42                 }
43             } */
44         })
45 
46         vm.$watch('isHot',{
47             immediate:true, //Let on initialization handler Call it
48             //handler When will it be called? When isHot When changes occur.
49             handler(newValue,oldValue){
50                 console.log('isHot It was modified',newValue,oldValue)
51             }
52         })
53     </script>
54 </html>

 

Summary:

Monitoring attribute watch:
1. When the monitored attribute changes, the callback function will be called automatically to perform relevant operations
2. The monitored attribute must exist before monitoring can be performed! You can make the attribute in data or calculate the attribute
3. Two ways of monitoring:
  (1). When new Vue is selected, the watch configuration is passed in (it is clearly known that monitoring is required at the initial stage)
  (2). Via VM$ Watch monitoring (monitoring added later)

 

3. deep monitoring

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Weather case_Depth monitoring</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             <h2>It's a fine day today{{info}}</h2>
13             <button @click="changeWeather">Switch weather</button>
14             <hr/>
15             <h3>a The value of is:{{numbers.a}}</h3>
16             <button @click="numbers.a++">Let me a+1</button>
17             <h3>b The value of is:{{numbers.b}}</h3>
18             <button @click="numbers.b++">Let me b+1</button>
19             <button @click="numbers = {a:666,b:888}">Completely replace numbers</button>
20             <!-- {{numbers.c.d.e}} -->
21         </div>
22     </body>
23 
24     <script type="text/javascript">
25         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
26         
27         const vm = new Vue({
28             el:'#root',
29             data:{
30                 isHot:true,
31                 numbers:{
32                     a:1,
33                     b:1,
34                     c:{
35                         d:{
36                             e:100
37                         }
38                     }
39                 }
40             },
41             computed:{
42                 info(){
43                     return this.isHot ? 'scorching hot' : 'pleasantly cool'
44                 }
45             },
46             methods: {
47                 changeWeather(){
48                     this.isHot = !this.isHot
49                 }
50             },
51             watch:{
52                 isHot:{
53                     // immediate:true, //Let the handler call during initialization
54                     //handler When will it be called? When isHot When changes occur.
55                     handler(newValue,oldValue){
56                         console.log('isHot It was modified',newValue,oldValue)
57                     }
58                 },
59                 //Monitor the change of an attribute in the multi-level structure. Note that quotation marks should be used before isHot It's abbreviated
60                 /* 'numbers.a':{
61                     handler(){
62                         console.log('a Changed ')
63                     }
64                 } */
65                 //Monitor the changes of all attributes in the multi-level structure
66                 numbers:{
67                     deep:true,  //Default to false,Turn on depth monitoring
68                     handler(){
69                         console.log('numbers Changed')
70                     }
71                 }
72             }
73         })
74 
75     </script>
76 </html>

 

 

Summary:

Deep monitoring:
(1). By default, the watch in Vue does not monitor the change of the internal value of the object (one layer).
(2). Configure deep:true to monitor changes in internal values of objects (multiple layers).
(3).Vue itself can monitor changes in the internal values of objects, no matter how many layers, such as numbers c. D. e, but the watch provided by Vue cannot be used by default!
(4). In consideration of efficiency, when using watch, it is decided whether to adopt deep monitoring according to the specific structure of data.

 

4. Monitoring attribute abbreviation

When monitoring a property without configuring immediate and deep, you can use the abbreviation, similar to the abbreviation of calculated property:

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8" />
 5         <title>Weather case_Monitoring properties_Abbreviation</title>
 6         <!-- introduce Vue -->
 7         <script type="text/javascript" src="js/vue.js"></script>
 8     </head>
 9     <body>
10         <!-- Prepare a container-->
11         <div id="root">
12             <h2>It's a fine day today{{info}}</h2>
13             <button @click="changeWeather">Switch weather</button>
14         </div>
15     </body>
16 
17     <script type="text/javascript">
18         Vue.config.productionTip = false //prevent vue Generate production prompts at startup.
19         
20         const vm = new Vue({
21             el:'#root',
22             data:{
23                 isHot:true,
24             },
25             computed:{
26                 info(){
27                     return this.isHot ? 'scorching hot' : 'pleasantly cool'
28                 }
29             },
30             methods: {
31                 changeWeather(){
32                     this.isHot = !this.isHot
33                 }
34             },
35             watch:{
36                 //Normal writing
37                 /* isHot:{
38                     // immediate:true, //Let the handler call during initialization
39                     // deep:true,//Depth monitoring
40                     handler(newValue,oldValue){
41                         console.log('isHot Modified '', newValue,oldValue)
42                     }
43                 }, */
44                 //Abbreviation
45                 /* isHot(newValue,oldValue){
46                     console.log('isHot Modified '', newValue,oldValue,this)
47                 } */
48             }
49         })
50 
51         //Normal writing
52         /* vm.$watch('isHot',{
53             immediate:true, //Let the handler call during initialization
54             deep:true,//Depth monitoring
55             handler(newValue,oldValue){
56                 console.log('isHot Modified '', newValue,oldValue)
57             }
58         }) */
59 
60         //Abbreviation
61         /* vm.$watch('isHot',(newValue,oldValue)=>{
62             console.log('isHot Modified '', newValue,oldValue,this)
63         }) */
64 
65     </script>
66 </html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

11

 

Keywords: Vue

Added by ashton321 on Thu, 27 Jan 2022 03:35:41 +0200