(9)vue 组件

 

1.基础

(1)最基本的组件

    <div id="components-v">
        <redBtn></redBtn>
    </div>

    <script>
        Vue.component('redbtn', {
            template: '<button style="background-color:red;100px;height:20px">红色按钮</button>'
        }
        )
        new Vue({
            el: '#components-v'
        })
    </script>

 (2)

    <div id="components-demo">
        <button-counter></button-counter>
    </div>
    <script>
        // 定义一个名为 button-counter 的新组件
        Vue.component('button-counter', {
          data: function () {
            return {
              count: 0
            }
          },
          template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
        })

        new Vue({
            el: '#components-demo'
        })
    </script>

data 必须是一个函数

先注册,才能在vue中使用。例如这个例子中如果把new vue 放到定义模板代码的上方,页面将不会显示。

2.组件命名

组件名称如果使用的是驼峰法命名 redBtn,则自定义元素使用时要写成 <red-btn></red-btn>

建议还是自定义元素和组件名称都写成 red-btn的方式

2.注册局部组件

        new Vue({
            el: '#components-v',
            components: {
                redbtn: {
                    template: '<button style="background-color:red;100px;height:20px">红色按钮</button>'
                }
            }
        })

3.传递数据

 使用props传递参数

    <div id="components-v">
        <redBtn btntext="红色按钮"></redBtn>
    </div>

    <script>
        Vue.component('redbtn', {
            props:['btntext'],
            template: '<button style="background-color:red;100px;height:20px">{{btntext}}</button>'
        }
        )
        new Vue({
            el: '#components-v'
        })
    </script>

3.父子组件

5.父子组件通讯

原文地址:https://www.cnblogs.com/buchizaodian/p/12286475.html