• 絮叨一下
  • 组件
  • 命名规则
  • 注册三种方式
  • 注意点
  • data
  • 写给看到最后的你

絮叨一下

已经是 vue系列的第五天啦 今天成功 步入到及其重要的知识点 组件的知识 这个地方 对于初学来说是有点 难 今天 分享一下 基础知识 一起进步 !!

组件

  • 概念: 组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。组件是vue中最强大的功能之一 他可以扩展 html元素 封装可重用代码

命名规则

命名规则

注册三种方式

全局



Vue.component("one", {
    template: "<p>我是第一个组建</p>"
});



局部



components: {
    one1: {
        template: "<p>123</p>"
    }
},
template:""



通过全局api Vue.extend



<body>

    <div id="app">
        <aa></aa>
    </div>

    <script>
        let ex = Vue.extend({
            template:"<div>这是个div</div>"
        });

        Vue.component("aa",ex);

        new Vue({
            el:"#app",
        });
        
    </script>
</body>



注意点

  • ul ol table select 这种元素包含的有限制 详细看下面的代码
<body>

    <table id="app">
        <!-- <one></one>  错误演示不会进行任何数据绑定-->
    </table>

    <template id="opt">
        <tr>
            <td>option1</td>
            <td>option2</td>
            <td>option3</td>
        </tr>
    </template>

    <script>
        new Vue({
            el:"#app",
            components:{
                one:{
                    template:"#opt"
                }
            }
        })
    </script>
</body>





vue template script styles顺序 vue template详解_vue template 复用


没有报错也没有输出

解决这种问题我们需要使用 is属性进行 更改 请看 <tr is="one"></tr>


<table id="app">
    <!-- <one></one>  错误演示不会进行任何数据绑定-->
    <tr is="one"></tr>  
</table>


vue template script styles顺序 vue template详解_公众号_02


好滴 成功输出啦

data

上面说组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等 但是这里要注意

data必须是一个函数

原因:

data是一个返回对象的函数,这样设计的目的是因为,组件是为了重复调用,但数据又要互相隔离。如果定义成一个对象的话,就会一变全变,所以得定义一个函数,封闭空间。实现了展示的效果一样,但数据又互相不影响。

看这个例子


<body>
    <div id="app">
        <one></one>
        <one></one>
    </div>

    <script>
        Vue.component("one", {
            template: "<button @click='add'>{{num}}</button>",
            data() {
                return {
                    num: 0
                }
            },
            methods: {
                add() {
                    this.num++
                }
            },
        })

        new Vue({
            el: "#app",
        })
    </script>
</body>


他们数据将相互 分离


vue template script styles顺序 vue template详解_公众号_03