单个组件的语法:

创建构造器
var MyComponent = Vue.extend({
        template: '<div>A custom component!</div>'
    });
    注册组件
Vue.component('my-component', MyComponent);

父子组件的写法:

 var child = Vue.extend({
        template:"<h1>我是孩子</h1>"
    });
      Vue.component("parent",{
          template:"<h1>我是父亲<child1></child1></h1>",
          components:{
              "child1":child
          }
      })

父子嵌套实例:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="vue.js" type="text/javascript"></script>
</head>
<body>
<div id="box">
    <parent></parent>
</div>
<script>
    window.onload=function(){
        new Vue({
            el:"#box"
        });
    };
    var child = Vue.extend({
        template:"<h1>我是孩子</h1>"
    });
      Vue.component("parent",{
          template:"<h1>我是父亲<child1></child1></h1>",
          components:{
              "child1":child
          }
      })
</script>

</body>
</html>

父子孙组件嵌套:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="vue.js" type="text/javascript"></script>
</head>
<body>
<div id="box">
    <parent></parent>
</div>
<script>
    window.onload=function(){
        new Vue({
            el:"#box"
        });
    };
    var child = Vue.extend({
        template:"<h1>我是孙子</h1>"
    });
    var son = Vue.extend({
        template:"<h1>我是儿子<child1></child1></h1>",
        components:{
            "child1":child
        }
    });
    Vue.component("parent",{
        template:"<h1>我是父亲<son1></son1></h1>",
        components:{
            "son1":son
        }
    })
</script>

</body>
</html>

父子组件另一种写法:

var vm=new Vue({
        el:"#box",
        data:{
            a:"aaa"
        },
        components:{
            "aaa":{
                template:"<h2>我是aaa</h2><bbb></bbb>",
                components:{
                    "bbb":{
                        template:"<h2>我是bbb</h2>",
                    }
                }
            }
        }
    })
<div id="box">
   <aaa></aaa>
</div>
Logo

前往低代码交流专区

更多推荐