VUE-父组件和子组件

一、父组件

        const cnp2 = Vue.extend({
            template: `
                <div>
                    <h2>我是构造器2</h2>
                    <cpn1></cpn1>
                </div>
            `,
            components: {
                cpn1: cnp1
            }
        })

二、子组件

        const cnp1 = Vue.extend({
            template: `
                <div>
                    <h2>我是构造器1</h2>
                </div>
            `
        })

解析:父组件和子组件的区分和造成。

当组件存在这种关系的时候,就存在父子关系--------当一个组件在另外一个组件中注册,这时候,被注册的组件是子组件,包含着子组件的就是父组件 html

*****完整代码****

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<div id="app">
    <cpn2></cpn2>
</div>

<body>
    <script>
        const cnp1 = Vue.extend({
            template: `
                <div>
                    <h2>我是构造器1</h2>
                </div>
            `
        })
        const cnp2 = Vue.extend({
            template: `
                <div>
                    <h2>我是构造器2</h2>
                    <cpn1></cpn1>
                </div>
            `,
            components: {
                cpn1: cnp1
            }
        })
        let vm = new Vue({
            el: '#app',
            data: () => ({}),
            components: {
                cpn2: cnp2
            }
        })
    </script>
</body>

</html>

 三、全局组件和局部组件的语法糖写法

优势:省去Vue.extend()的这种写法,直接用一个对象代替

一、全局组件语法糖vue

        Vue.component('mycpn', {
            template: `
                <h2>全局组件,语法糖写法</h2>
            `
        })

二、局部组件语法糖app

            components: {
                mycpn: {
                    template: `
                    <h2>局部组件,语法糖写法</h2>
                    `
                }
            }

*****完整代码****

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<div id="app">
    <mycpn />
</div>
<div id="app2">
    <mycpn />
</div>

<body>
    <script>
        Vue.component('mycpn', {
            template: `
                <h2>全局组件,语法糖写法</h2>
            `
        })

        let vm = new Vue({
            el: '#app',
            components: {
                mycpn: {
                    template: `
                    <h2>局部组件,语法糖写法</h2>
                    `
                }
            },

        })
        let vm2 = new Vue({
            el: '#app2'
        })
    </script>
</body>

</html>
相关文章
相关标签/搜索