Vue

Vue的组件component

一什么是component

说白了,就是一个HTML页面上,页头、页脚、sidebar,等都可以称之为组件。引用官网的原话例子,可能比较好理解。

For example, you might have components for a header, sidebar, and content area, each typically containing other components for navigation links, blog posts, etc.

To use these components in templates, they must be registered so that Vue knows about them. There are two types of component registration: global and local. So far, we’ve only registered components globally, using Vue.component:

Vue.component('my-component-name', {
  // ... options ...
})

二 一个component demo

官网链接:https://vuejs.org/v2/guide/components.html

思路和流程:

1 新建1个HTML文件;
2 HTML中引用Vue.js;
3 script标签中自定义组件;
4 body标签中使用自定义的组件
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>第1个自定义组件</title>
        <script src="../vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div id="cust">
            <ul>
              <the-component></the-component>
            </ul>
        </div>

        <script type="text/javascript">
            Vue.component('the-component',{
                data:function(){
                    return{
                        count:0
                    }
                },
                template:'<button v-on:click="count++"> You have clicked me {{count}} times. </button>'
            })

            let app=new Vue({
                el:'#cust',
            })
        </script>   
    </body>
</html>
5 血的经验

自定义组件名,首字符不要大写,否则报错!!!!!

vue.js:634 [Vue warn]: Unknown custom element: <the-component> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in <Root>)

三 一个关联数据的自定义组件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>关联属性的组件</title>
        <script src="../vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>

        <div id="app">
            <ul>
                <my-comp-list v-for="item in items" v-bind:item="item"></my-comp-list>
            </ul>       
        </div>      

        <script type="text/javascript">
              Vue.component('my-comp-list',{
                  props:["item"],
                  template:'<li>{{item}} </li>'
              })
            let app= new Vue({
                el:'#app',
                data:{
                    items:['Java','Vue','PostgreSQL']
                }
            })
        </script>
    </body>
</html>

思路:

首先,在Vue实例,new Vue({})里,定义一个数据层即Model,对象data,其里面包含一个数组items;

其次,在自定义组件里,定义模板template,让这个列表里关联到上述定义的Model层;template:'{{item}} ‘;

然后,要想使用,还需要在自定义组件里定义属性props,让它和template里定义的{{item}}关联起来;

接着,在使用的自定义组件的地方,使用v-for来做列表渲染;v-for=”item in items”,这里的items就是

留言