学习笔记Vue(九)——组件components

组件是可复用的 Vue 实例,且带有一个名字,可以在html中以一个标签的形式使用组件。
组件中有自己的data,是一个函数的形式,return一个对象,里面包含的值可以在他的template中使用。
template里的内容会渲染在html中的组件标签里。
在components里写的组件名要使用小驼峰式写法,但在html标签里要转换成小写中间以一个横杠分隔。
例子:
全局组件:

<body>
	<div id="app">
        <hello-world></hello-world>
    </div>

	<script>
		//全局组件component  不带s
         Vue.component('hello-world',{   
         //组件命名,连字符式   或者驼峰式  但标签必须都写连字符式  html标签里不允许大写
             data (){
                 return {
                     msg: 'hello world!!!'
                 }
             },
             template: '<div>{{msg}}</div>'
         })
     </script>
 </body>

局部组件:

<body>
	<div id="app">
        <hello-world></hello-world>
    </div>

	<script>
		var vm = new Vue({
            el: '#app',
            data: {
            },
            //局部属性里components要加s
            components: {
                helloWorld:{
                    data (){
                        return {
                            msg: 'hello world!!!'
                        }
                    },
                    template: '<div>{{msg}}</div>'
                }
            }
        })
     </script>
 </body>
Prop属性

Prop 是你可以在组件上注册的一些自定义特性。
通过代码来讲解:

<body>
    <div id="app">
        <my-content a="1" b="2" :title="9" :content="content"></my-content>
    </div>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                content: 'jskjklsjkldfj',
                title: 'jjjjj'
            },
            components: {
                myContent: {
                    // props:['title','content'],
                    props: {
                        content: {
                            type: String, //值的类型
                            default: 'kkkkkkkkkkkk' // 默认值
                        },
                        title: {
                            type: Number,
                            validator (value) { //自定义验证函数
                                return value >=10
                            },
                            required: true
                        },
                        arr: {
                            type: Array,
                            default: ()=> [1, 2, 3]
                        }
                    },
                    template:`<div>
                        <h3>{{title}}</h3>
                        <p>{{content}}</p>
                    </div>`
                }
            }

        });
    </script>
</body>

由于上面的title值不符合验证,控制台会报一个错,但不影响显示
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值