组件
组件基础
- 组件 组件名称 多个单词之间用短横线来连接html
<com-a></com-a>
- 单标签形式书写 在单文件组件中有用html
<com-a />
- 组件包含了 html css js 的代码块 主要是对页面中某个功能块的封装 实现功能模块的复用
- 全局注册js
var comA = { // 模板 template: ` <p>a组件</p> ` } // app.component(组件名称, 组件对象) // 可以使用驼峰命名法 也可使用"-"连接 app.component('comA', comA)
- 局部注册js
// 局部注册 components: { 'com-b': comB, 'com-a': comA }
- 内部注册js
var comB = { template: ` <p>我是组件B</p> <com-a></com-a> ` // components: { // 'com-a': comA // } }
组件模板
- 使用 script 定义组件模板
- 默认不支持 html 代码 修改标签类型 type="text/html"
- html
<script type="text/html" id="com-b"> <p>我是b组件</p> <p>我是b组件内容</p> <com-c></com-c> </script>
jsvar comB = { template: '#com-b' components: { comC } }
- 使用 template 标签 创建组件模板
- html
<template id="com-c"> <p>我是c组件</p> <p>我是c组件的内容</p> </template>
- js
var comC = { template: '#com-c' } // 全局注册 无论在那个组件都可以用 app.component('comC', comC)
- js
var comA = { template: `<p>我是a组件</p>` }
- 根组件 也是一个组件只不过是 最底层的组件
- 全局注册与局部注册
- 全局注册 无论在那个组件都可以用
- 局部注册 只能在当前组件可用
组件中的 data 数据
- 组件中的 data 数据是不能共用的
- 只能在当前组件使用
- 组件中的内容只能在当前组件中使用
- 子组件无法用根组件的数据
特殊标签内的组件
使用is属性
- 例如:is="vue:组件名" 将标签替换为我们想要的组件
组件传值数据验证
- props 用来接收父组件传递过来的参数
- props: ['msg'] // 可以定义多个属性名称用来接收数据 是以字符串的形式书写
- 对象形式分类
- js
msg: String,
- 多类型
- 必传项
- 默认值
- 自定义验证器
- js
props: { // msg属性接收字符串类型的数据 // 不满足这个数据类型就会报警告 // msg: String, // 多类型 只要是String, Number // msg: [String, Number] // 必传项 // msg: { // type: Boolean, // // required 值为true 就表示 是一个必传项 // required: true // } // 默认值 msg: { type: String, // default: '我是默认值' default() { return '我是默认值' } }, obj: { type: Object, // 对象或者数组指定默认值必须写成工厂函数形式 // default: { name: 'ls', age: 20 } default() { return { name: 'ls', age: 20 } } }, foo: { type: Function, // default: function(){} // default() {} 就是foo的默认值 default() { console.log('默认方法执行了') } }, sex: { // 自定义验证器 validator(value) { // console.log(value) // 传递的值必须是0,1,2 其中的一个 // 返回ture 验证通过 返回false 验证不通过 return [0, 1, 2].includes(value) } } },
组件继承
- 在组件上定义的属性没有接收就会默认展示在子组件的根标签
v-bind="$attrs" 将属性添加到指定的标签元素上
- 简写形式html
<p :="$attrs">我是子组件</p>
- 默认 多个根标签则 属性没有被添加
- 需要添加时使用
:="$attrs"
添加就可以了 - 组件接收数据依赖于标签的属性 props
- inheritAttrs
- 用来控制组件属性是否应该被继承道标签上
- 手动添加的属性是不会被禁止的