Components of Vue learning notes

Time:2020-3-25

Like it first, then pay attention to it, form a habit and then watch it.
Message: no winter will not pass, no spring will not come.

Preface

In some of the previous blogs of Vue, we have almost finished learning the foundation of Vue, and from this blog, we will enter another stage of learning of Vue. The content of this blog accounts for a large proportion in the future Vue projects, so the partners need to study carefully. The content of this blog is also relatively simple. Everyone who has read my blog knows that I have written every one Blog posts are very detailed, so don’t worry about learning. I will try my best to explain what I have learned in a simple and easy way, so that everyone can learn more happily. Let’s have a look!

What can you get after learning

  • Learn to use global and local components
  • Learn ref reference

Initial component

Interpretation:

Component system is another important concept of Vue, because it is an abstraction that allows us to build large-scale applications with small, independent and often reusable components. When you think about it, almost any type of application interface can be abstracted into a component tree.

Components of Vue learning notes

Component unit division

Components can usually be used to makeSingle page application (SPA)

Components can be divided into two categories:

Local and global components

Global component

There is no doubt that global components can be accessed in many places.
Syntax:

1vue. Component ('component name ', {2template:' template '3})
Global component registration method 1
1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > global component registration method 1 < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9 < T1 > < T1 > 10 < / div > 11 < div id = "demo" > 12 < T1 > < T1 > 13 < / div > 14 < script type = "text / template" id = "template1" > 15 < div > this is a component < / div > 16 < / script > 17 < script SRC = ".. / JS / Vue. JS" type= "text/javascript" charset="utf-8"></script>18        <script type="text/javascript">19            Vue.component('t1', {20                template:'#template1'21            })22            let vm=new Vue({23                el:'#app'24            })25            let d=new Vue({26                el:'#demo'27            })28        </script>29     </body>30</html>

First, we use the script tag to define the template and then register the template in the component. Here we define two Vue instances. We find that they can be used in demo and app, which proves that the global component registration is successful. This is the first way to define the component. Next, we learn the second way.

Global component registration method 2
1<!DOCTYPE html> 2<html> 3    <head> 4        <meta charset="UTF-8"> 5        <title></title> 6    </head> 7    <body> 8        <div id="app">  9 < template > < template > 10 < / div > 11 < template id = "template1" > 12 < div > this is a component < / div > 13 < / template > 14 < div id = "demo" > 15 < template > < 16 < / div > 17 < script SRC = ".. / JS / Vue. JS" type = "text / Java script" charset="utf-8"></script>18        <script type="text/javascript">19            Vue.component('temp',{20                template:'#template1'21            })22            let vm=new Vue({23                el:'#app', 24                data:{2526                },27                methods:{2829                }, 30                computed:{3132                }33            })34            let app=new Vue({35                el:'#demo'36            })37        </script>38    </body>39</html>

In the second way, we can directly use the template tag provided by Vue to define the template and then register it in the component.

Global component registration method 3
1<!DOCTYPE html> 2<html> 3    <head> 4        <meta charset="UTF-8"> 5        <title></title> 6    </head> 7    <body> 8        <div id="app">  9            <my-compent></my-compent>10        </div>11        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>12        <script type="text/javascript">13            Vue.component('myCompent', {14 template: '< div > this is the third way to define components. 16 let VM = new Vue ({17 El:' ා app ', 18 data: {1920}, 21                methods:{2223                },24                computed:{2526                }2728            })2930        </script>31    </body>32</html>

This is the third way to define global components, which can be used in all three ways. It mainly depends on personal habits. Anyway, I prefer the third way. The registration of global components is over here. Next, I will mainly discuss the local component genealogy.

Local components

Local components are defined in the Vue instance.

Local components are only valid in the current Vue instance.

Local component registration
1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > local component registration < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9            <hello></hello>10            <!--<hi></hi>-->11        </div>12        <div id="demo">13            <hi></hi>14            <!--<hello></hello>-->15        </div>16        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>17         <script type="text/javascript">18            let vm1=new Vue({19                el:'#app',20                data:{2122                },23                methods:{2425                }, 26. Calculated: {2728}, 29. Components: {30 'hello': {31. Template: '< div > My name is hello, What's your name < / div > '32} 33} 34}) 35 let vm2 = new Vue ({36 El:' ා demo ', 37. Components: {38 'Hi': {39 template: '< div > My name is hi, what's your name? < div >' 40} 41} 42}) 43 < / script > 44 < / body > 45</html>

As a result, I won’t post it. You can try it if we use hi component in app or hello component in demo.

Vue will give a warning because we are registering local components, so we can’t use them.

Ref reference

Before introducing ref reference, I want to take you to implement a small demo. The requirements are as follows: there are four buttons on the page: red, yellow, green and blue. When we click a button, the corresponding color will be displayed, as shown in the following figure:

Components of Vue learning notes

When we click red, it will display red, and so on. Let me take you to implement this small demo! Of course, it is the knowledge of application components, after all, strike while the iron is hot.

Add component layout
1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref reference < / Title > 6 < style type = "text / CSS" > 7. Box {8 width: 200px; 9 Height: 200px; 10                border: 2px solid black;11                margin-top: 10px; 12            }13        </style>14    </head>15    <body>16        <div id="app">17            <color-template></color-template>18        </div>19        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>20        <script type="text/javascript">2 1            let vm=new Vue({22                el:'#app',23                data:{2425                },26                methods:{2728                },29                computed:{3031                }, 32                components:{33                    colorTemplate:{34                        data(){35                            return{36                                colorArray:['red','yellow','green', 'blue']37                            }38                        }, 39                        template:`<div class="btn_group">40                            <button v-for="color in colorArray" :style="{background:color}">{{color}}</button>41                            <div class="box"></div>42                         </div>`,43                    }44                }45            })4647        </script>48    </body>49</html>

Result:

Components of Vue learning notes

Here we define the local component, and then return the array corresponding to the color in the local component. When rendering, we render the color to the corresponding button, and bind the corresponding background color for each button.

Binding events

Next, we add events for each button, and then click to get the corresponding color. We can pass in the corresponding color value name in the event

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref reference < / Title > 6 < style type = "text / CSS" > 7. Box {8 width: 200px; 9 Height: 200px; 10                border: 2px solid black;11                margin-top: 10px; 12            }13        </style>14    </head>15    <body>16        <div id="app">17            <color-template></color-template>18        </div>19        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>20        <script type="text/javascript">2 1            let vm=new Vue({22                el:'#app',23                data:{2425                },26                methods:{2728                },29                computed:{3031                }, 32                components:{33                    colorTemplate:{34                        data(){35                            return{36                                colorArray:['red','yellow','green', 'blue']37                            }38                        }, 39                        template:`<div class="btn_group">40                            <button v-for="color in colorArray" :style="{background:color}" @click="handleClick(color)">{{color}}</button>41                            <div class="box"></div>42                         </div>`,43                        methods:{44                            handleClick(color){45                                console.log(color); 46                            }47                        }48                    }49                }50            })5152        </script>53    </body>54</html>

Result:

Components of Vue learning notes

Design sketch

When we click the corresponding button in turn, the value of the corresponding color has been obtained. Of course, we have realized this function now. But in order to consolidate the previous knowledge, I will also teach you to use another method to obtain is the use of dataset mentioned below.

Use of dataset

The data XX attribute is added in HTML5. We know that data XX can be used to store data, so we can also save the corresponding color in data XX, and then get it through dataset.

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref reference < / Title > 6 < style type = "text / CSS" > 7. Box {8 width: 200px; 9 Height: 200px; 10                border: 2px solid black;11                margin-top: 10px; 12            }13        </style>14    </head>15    <body>16        <div id="app">17            <color-template></color-template>18        </div>19        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>20        <script type="text/javascript">2 1            let vm=new Vue({22                el:'#app',23                data:{2425                },26                methods:{2728                },29                computed:{3031                }, 32                components:{33                    colorTemplate:{34                        data(){35                            return{36                                colorArray:['red','yellow','green', 'blue']37                            }38                        }, 39                        template:`<div class="btn_group">40                            <button v-for="color in colorArray" :style="{background:color}" @click="handleClick" :data-color="color">{{color}}</button>41                            <div class="box"></ div>42                        </div>`,43                        methods:{44                            handleClick(e){45                                const color=e.target.dataset.color; 46                                console.log(color); 47                            }48                        }49                    }50                }51            })5253        </script>54    </body>55</html>

Using this method, you can click one by one to get the value of the corresponding color. If the result is the same as the above result, I will not take a screenshot here.

Realization effect

After obtaining the corresponding color, we need to achieve the above effect. Now we must use ref reference

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref reference < / Title > 6 < style type = "text / CSS" > 7. Box {8 width: 200px; 9 Height: 200px; 10                border: 2px solid black;11                margin-top: 10px; 12            }13        </style>14    </head>15    <body>16        <div id="app">17            <color-template></color-template>18        </div>19        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>20        <script type="text/javascript">2 1            let vm=new Vue({22                el:'#app',23                data:{2425                },26                methods:{2728                },29                computed:{3031                }, 32                components:{33                    colorTemplate:{34                        data(){35                            return{36                                colorArray:['red','yellow','green', 'blue']37                            }38                        }, 39                        template:`<div class="btn_group">40                            <button v-for="color in colorArray" :style="{background:color}" @click="handleClick(color)" :data-color="color">{{color}}</button>41                            <div class=" box" ref="squareBox"></div>42                        </div>`,43                        methods:{44                            handleClick(color){45                                const box=this.$refs.squareBox; 46                                box.style.backgroundColor=color; 47                            }48                        }49                    }50                }51            })5253        </script>54    </body>55</html>

Result:

Components of Vue learning notes

We have achieved the effect, but we still don’t know what ref is. Don’t worry, and listen to me.

We know that JavaScript operation DOM is very performance consuming

Therefore, in Vue, we provide ref to get the corresponding DOM element. The method is this. $refs to get all DOM elements with ref reference.

There are mainly four types, as follows.

Independent binding

When Binding alone, it is mainly to obtain the corresponding DOM elements, just like the native JavaScript elements or the $elements in jQuery. See the example below.

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref bind separately < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9 < div ref = "square_box" class = "box" > ew Vue({15                el:'#app',16                data:{1718                },19                methods:{20                    handleClick(){21                        var dom=document.getElementsByClassName('box')[0]; 22                       console.log(this.$refs.square_box);23                        console.log(dom);24                    }25                }, 26                computed:{2728                }2930            })3132        </script>33    </body>34</html>

In this example, we use two methods to get DOM elements,

One is to use ref to get, the other is to use native JavaScript to get.

You can see that both methods get DOM elements.
Result:

Components of Vue learning notes

Binding duplicate elements

In JavaScript, we get the same node throughDocument. Getelementsbyclassname (‘node name ‘)perhapsDocument. Getelementbyname (‘node name ‘), but jQuery uses $, which returns an array, but after the ref binds multiple identical elements, the latter will overwrite the former, which is the magic aspect of ref binding elements.

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref bind duplicate elements < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9 < div class = "box" ref = "V" box "> type="text/javascript">15            let vm=new Vue({16                el:'#app',17                data:{1819                }, 20                methods:{21                    hanldeClick(){22                        var doms=document.getElementsByClassName('box');23                        console.log(doms);24                       console.log(this.$refs.v_box); 25                    }26                },27                computed:{2829                }3031            })3233        </script>34    </body>35</html>

In this example, we also use the above two methods to obtain the elements, so that the comparison results will come out. Only one element is obtained by using ref, that is, the last written element will overwrite the previous one. In a word, no matter how many repeated elements use ref, the last result will always be returned.
Result:

Components of Vue learning notes

Design sketch

The effect of ref implementation in V-for

If there is such a requirement in the actual project, how about binding multiple identical elements? It’s easy to use V-for.

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > the effect of ref implementation in V-for < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9 < template V-for = "index of 10" > 10 < div class = "box" ref = "F" box "> < div > 11 < / template > 12 < button @ Click =" handleclick "> get element < / button > 13 < / div > 14 < script SRC =".. / JS / Vue. JS "type =" text / JavaScript "charset =" ut " f-8"></script>15        <script type="text/javascript">16            let vm=new Vue({17                el:'#app',18                data:{1920                }, 21                methods:{22                    handleClick(){23                        console.log(this.$refs.f_box);24                        let doms=document.getElementsByClassName('box');25                        console.log(doms); 26                    }27                },28                computed:{2930                }3132            })3334        </script>35    </body>36</html>

We still use two methods to get nodes. Now, we find that the DOM element obtained in the V-for loop using ref is an array (Collection), and the native JavaScript is still the same as before.

Components of Vue learning notes

Design sketch

Binding components

The power of ref lies not only in the first three aspects, but also in binding components?Binding component returns component instance (Application of component is instance object of component)

This can also be said to be of some use. This is also the last item that REF needs to introduce.

1 <! DOCTYPE HTML > 2 < HTML > 3 < head > 4 < meta charset = "UTF-8" > 5 < title > ref bind component < / Title > 6 < / head > 7 < body > 8 < div id = "app" > 9 < Hello ref = "hello" >                el:'#app',16                data:{1718                },19                methods:{20                    handleClick(){21                        console.log(this.$refs.hello); 22} 23}, 24 computed: {2526}, 27 components: {28 'hello': {29 'template': '< div > Hello < / div >', 30                    }31                }32            })33        </script>34    </body>35</html>

Result:

Components of Vue learning notes

Design sketch

You can see that the ref binding component returns the component instance. I have explained the use of ref here. Generally speaking, ref is relatively simple.

Ending

If you think this article is useful to you, please lighten thatClick button

For the warm man Muzha (a wandering KK):It’s really useful, your support is the driving force for me to move forward. See next article.

Be careful:Blog Park, CSDN and other websites contain the nickname of a wandering KK, which belongs to the author. As for why we use the nickname of Ertaizi Muzha, I think there will be relevant articles to explain.

Author:A wandering KK two Prince Muzha

It’s not easy to be original. Please don’t go whoring for nothing.
Mu Zha, the second prince, is a little white who lives in front of the Internet. He focuses on front-end development and is good at sharing technology.
If you need to reprint, please contact the author or keep the link, WeChat official account search Prince Mu Zha two.