Two registration methods of basic components of Vue learning components Application of dynamic components

The concept of components

Components are one of the powerful features of Vue, which are used to extend HTML elements and encapsulate reusable code. It can be said that when the componentCustom HTML tags. The essence of the component isReusable Vue instance, so they receive the same options as new Vue(), (except for the el attribute which is specific to the root instance).

Component registration and use

After creating a new component in Vue, in order to be used in the template, these components must first be registered so that Vue can recognize it. There are two registration types in Vue:global registrationandpartial registration

global registration

A globally registered component can be used in any newly created Vue instance after its registration

Registration and use of global components

1. How to register global components

  • the first way

FirstUse the Vue.extend global methodBuild the template object, thenVia the Vue.component methodto register the component. Because the component will be parsed into custom HTML code in the end, you can directly use the registered component name as a tag in HTML.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <hello></hello>
    </div>
</body>
<script>
    //创建模板对象,利用Vue的全局方法extend 
    var MyComponent = Vue.extend({
    
    
        template: `<h3>hello world</h3>`
    })

    //根据模板对象注册组件,利用Vue的comppnent方法
    Vue.component('hello', MyComponent)

    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    }
    })
</script>

</html>

insert image description here
You can see that the component is parsed into an HTML element

  • the second way

Register global components directly in Vue.component in a way similar to anonymous objects in C#

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
        <my-hello2></my-hello2>
    </div>
</body>
<script>

    //根据模板对象注册组件,利用Vue的comppnent方法
    Vue.component('myHello', Vue.extend({
    
    
        template: `<h3>hello world</h3>`
    }))

    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    }
    })
</script>

</html>

Vue.extend can be omitted

//这样写更加简略
    Vue.component('myHello', {
    
    
        template: `<h3>hello world</h3>`
    })
  • Experience the use of global components
  • After knowing the registration method of the global registration component, let's use an example to experience the use of the global component
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
        <my-hello2></my-hello2>
    </div>

    <div id="app2">
        <my-hello></my-hello>
        <my-hello2></my-hello2>
    </div>
</body>
<script>

    //根据模板对象注册组件,利用Vue的comppnent方法
    Vue.component('myHello', {
    
    
        template: `<h3>hello world</h3>`
    })

    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    }
    })

    var vm2 = new Vue({
    
    
        el: "#app2",
        data: {
    
    }
    })
</script>

</html>

Here, two Vue instance objects are created. The globally registered components can act on the boxes bound by the two instances at the same time.

insert image description here

  • Use the template tag to define a template

In the previous example, only simple HTML code is defined in the template attribute. In practical applications, the template content pointed to by the template attribute may contain many elements, and the template created with Vue.entend must have and only have one root element. Therefore, when you need to create a template with complex elements, you can wrap a div on the outermost layer

    Vue.component('myHello', {
    
    
        template: `<h3>hello world</h3><h4>hello world2</h4>`
    })

Like this, it throws an error for lack of root element
insert image description here

    Vue.component('myHello', {
    
    
        template: `<div><h3>hello world</h3><h4>hello world2</h4></div>`
    })

Set layer div can be solved
insert image description here

But it is not beautiful and convenient to write like this.

In order to facilitate development, we use the template tag to define the template in the code section, and take an id for it,Specify the template by id when registering the component

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
    </div>
    <template id="tmp1">
        <div>
            <h3>hello world</h3>
            <h4>hello world2</h4>
        </div>
    </template>
</body>

<script>

    //根据模板对象注册组件,利用Vue的comppnent方法
    Vue.component('myHello', {
    
    
        template: "#tmp1"
    })

    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    }
    })

</script>

</html>
  • data options in custom components

When customizing components,The data option must be a function, through the function to return the object.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
    </div>
    <template id="tmp1">
        <div>
            <h3>hello world</h3>
            <h4>{
    
    {
    
    msg}}</h4>
            <button @click="tanchuang">弹窗</button>
        </div>
    </template>
</body>

<script>

    //根据模板对象注册组件,利用Vue的comppnent方法
    Vue.component('myHello', {
    
    
        template: "#tmp1",
        data: () => {
    
       //此处data必须是个函数,通过函数返回对象
            return {
    
    
                msg: "你好!!!"
            }
        },
        methods: {
    
    
            tanchuang: function(){
    
    
                alert(this.msg)
            }
        }
    })

    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    }
    })

</script>

</html>

The effect is as follows:
insert image description here

A custom component is like a Vue instance. It not only has data attributes, but also has methods options to define the behavior methods of elements in a component.
When the button is clicked:
![Insert picture description here](https://img-blog.csdnimg.cn/68c658b7c5654a828ff0b65442110863.png

Registration and use of local components

  • Basic usage of local components

The so-called local components are components that can only be used in a certain instance. Local components are in an instanceRegister via the components optionof.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
    </div>
    <template id="tmp1">
        <div>
            <h3>hello world</h3>
            <h4>{
    
    {
    
    msg}}</h4>
            <button @click="tanchuang">弹窗</button>
        </div>
    </template>
</body>

<script>

    //根据模板对象注册组件,利用Vue的comppnent方法


    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    },
        components: {
    
    
            myHello: {
    
    
                template: "#tmp1",
                data: function () {
    
    
                    return {
    
    
                        msg: "你好!!!"
                    }
                },
                methods: {
    
    
                    tanchuang: function () {
    
    
                        alert(this.msg)
                    }
                }
            }
        }
    })

</script>

</html>

Note: Using partial registration to register components can only work in the current instance object, and DOM objects bound to other instances cannot parse Vue custom components.

  • Simplify the component into an object:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-hello></my-hello>
    </div>
    <template id="tmp1">
        <div>
            <h3>hello world</h3>
            <h4>{
    
    {
    
    msg}}</h4>
            <button @click="tanchuang">弹窗</button>
        </div>
    </template>
</body>

<script>

    var zujian = {
    
    
        myHello: {
    
    
            template: "#tmp1",
            data: function () {
    
    
                return {
    
    
                    msg: "你好!!!"
                }
            },
            methods: {
    
    
                tanchuang: function () {
    
    
                    alert(this.msg)
                }
            }
        }
    }


    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    },
        components: zujian  //这里不能用引号引起来
    })

</script>

</html>

Application of dynamic components

The so-called dynamic components aremultiple componentsexistthe same locationDisplay, but not at the same time, for example, display a component when certain conditions are met, and display b component when other conditions are met. That is to say, multiple components use the same mount point, and then dynamically switch between multiple components. This effect can be achieved through v-show, but it is more troublesome. We generally use the built-in component component to achieve it.

Application of built-in component component

The built-in component component needs to be used to determine which component is rendered according to the value of the is attribute.Which component is displayed if the value of the is attribute is the name of the component

<component is:"组件名"></component>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <button @click="current='my-hello'">显示hello组件</button>
        <button @click="current='my-world'">显示world组件</button>
        <div>
            <!-- <my-hello></my-hello>
            <my-world></my-world> -->
            <component :is="current"></component>
        </div>
    </div>
</body>
<script>
    var vm = new Vue({
    
    
        el: "#app",
        data: {
    
    
            current: "my-hello"
        },

        //定义局部组件 在某个Vue实例内部定义 通过component属性定义
        components: {
    
    
            'my-hello': {
    
    
                template: `<h3>我是hello组件</h3>`,
                data() {
    
    
                    return {
    
    
                        x: Math.random() //产生一个随机数
                    }
                }
            },
            'my-world': {
    
    
                template: `<h3>我是world组件</h3>`,
                data() {
    
    
                    return {
    
    
                        y: Math.random()
                    }
                }
            }
        }
    })
</script>

</html>

Running effect:
insert image description here
click the second button:
insert image description here

Add the variable xy to the content of the two components

template: `<h3>我是hello组件{
     
     {x}}</h3>`,
template: `<h3>我是world组件{
     
     {y}}</h3>`,

insert image description here
insert image description here
Every time you jump back from another button, the random number will change

This shows that inactive components will be destroyed and recreated every time a component is switched, which is relatively inefficient, so how to cache the content of inactive components, that is, save the state of inactive components, and avoid re-rendering every time you switch.
We can use the built-in component keep-alive

  • Application of built-in component keep-alive

Wrap component components with keep-alive components to cache inactive component content.

<keep-alive>
     <component :is="current"></component>
</keep-alive>

Guess you like

Origin blog.csdn.net/fuhao6363/article/details/129595850