准备:
使用vue-cli新建一个webpack项目
注册组件:
打开创建的项目,在component文件夹中新建一个Loading文件夹,在Loading文件夹下新建两个文件,Loading.vue和index.js.

其中Loading.vue为子组件模板,index.js文件是用来把子组件模块导出。
Loading.vue只是简单显示一下Loading文字,如下:

接下来需要将组件注册并导出,index.js代码如下:

上面代码第一行是导入组件Loading
3-7行就是注册组件,需要注意的是Vue.component方法的第一个参数是组件使用时的名字,比如我上面定义的是fire-loading,那么在使用的时候就用<fire-loading><fire-loading/>,第二个参数就是所要注册的组件。
最后一行则是将内容导出
最后一步在main.js文件中引入

现在你可以在任何想用这个组件的地方插入了 组件相应的样式和js代码可以直接写在第一步中的文件之中!
比如我们在项目自动生成的Hello.vue中使用,

显示效果如下:

现在就已经成功加载上我们自定义的组件了。
父组件传值给子组件
首先在子组件loading.vue中声明props,然后就可以像vue data中的数据一样使用两个大括号来使用它

接下来在父组件中引用子组件的地方添加在上面props中声明的属性,属性名需要保持一致

则会看到如下效果:

如果需要动态绑定到父组件的数据 只需要使用v-bind ,简写使用冒号:

效果也是一样的

子组件给父组件传递数据
父组件可以使用 props 给子组件传递数据,那么反过来呢?该自定义事件出场了!
使用 v-on 绑定自定义事件
每个 Vue 实例都实现了事件接口 Events interface,即:
使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件
另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
下面我们写个例子
首先我们在子组件中添加一个button,定义一个v-on:click事件,在事件的处理函数中将该事件分发给父组件

然后在父组件中插入子组件的地方使用v-on:(子组件分发的事件名称)来获取子组件传递的数据

如上图所示,我们将传递的数据以弹出框的形式显示出来,效果如下

现在我们就成功获取到子组件传递给父组件的数据了。
slot的用法
单个 Slot
除非子组件模板中,包含至少一个插口,否则父组件的内容将会被丢弃。当子组件模板中只有一个没有属性的 slot 时,父组件的内容片段将会整个插入到子组件中 slot 所在的 DOM 位置,并替换掉 slot 标签本身。
最初在标签中的任何内容,都被视为备用内容。备用内容在子组件作用域内编译,并且只有在宿主元素为空,且没有要插入的内容时才显示备用内容。
下面我们来个例子
在子组件原有代码的基础上在button的下面添加一对slot标签

在父组件中的子组件使用的地方插入一对p标签

那么就会显示如下效果

如果我把slot标签移动到button标签的上面

那么大家就应该能猜到会有什么效果了吧

所以slot又会被叫做插槽
具名 Slot
元素有一个特殊的name属性,可以用于深度定制如何分发内容。可以给多个 slot 分配不同的名字。一个具有名称的 slot,会匹配内容片段中有对应slot属性的元素。
我们再来做个例子,我们在子组件模板中定义两个插槽slot,一个位于顶部,一个位于底部

在父组件定义两个p标签

显示如下效果

今天就写这么多了,后续还会坚持,持续更新补充
网友评论