(六)Component初识组件

本节知识点

  • 组件识vue的核心,必须要学好。组件就是自定义标签。这些标签在HTML中是没有的比如<hello></hello>
  • Vue.conmponent

(一)全局化组件

全局化就是在构造器外部使用Vue.component来注册

  • 全局组件必须要写在实例化前面

代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
<!--最初的组件调用开始-->
<div id="app">
    <hello> </hello>
</div>
<!--最初的组件调用结束-->
<div id="app2">
     <hello></hello>
</div>
</body>
<script>
Vue.component("hello",{
    template:`<p style="color:red;">全局组件</p>`
})
    var app = new Vue({
        el:"#app"
    })
var app2 = new Vue({
    el:"#app2"
})
</script>
</html>

  • 这样可以看到组件在不同的构造器里面都能使用

局部化组件 只能在规定的组件里面使用。出了组件使用不了

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
    <title>Title</title>
    <script src="js/vue.js"></script>
</head>
<body>
<!--最初的组件调用开始-->
<div id="app">
    <hello> </hello>
</div>
<!--最初的组件调用结束-->
<div id="app2">
     <hello></hello>
</div>
<!--局部化组件开始-->
<div id="app3">
      <haha> </haha>
</div>
<!--局部化组件结束-->
</body>
<script>
Vue.component("hello",{
    template:`<p style="color:red;">全局组件</p>`
})
var app = new Vue({
        el:"#app"
})
var app2 = new Vue({
    el:"#app2"
})
var app3 = new Vue({
    el:"#app3",
    components:{
        "haha":{
            template:`<p style="color:red;">局部化组件</p>`
        }
    }
})
</script>
</html>

特别注意的就是components后面必须要有s否则不起作用 局部的就只能局部使用,出了容器就使用不了
局部加S ,全局不加S

Vue.component和Vue.extend的区别

  • extend 是构造一个组件的语法容器。简单来说你给他参数他给你一个组件。然后这个组件你可以作用到Vue.component这个全局注册方法里,任意vue模板均可使用
var hello = Vue.extend({xxxxx});
Vue.component("hello",hello);

你也可以作用到局部中

new Vue({
  components:{
    hello:hello
   }
})

所以两者是不一样的。Vue.extend创建以后必须要挂载。而Vue.component不需要

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容