分分钟玩转Vue.js组件(二)(3)

<modal-dialog v-bind:show.sync="show" v-bind:class="dialogClass"> <header slot="header"> <h1>提示信息</h1> </header> <div slot="body"> <p>你想在对话框中放什么内容都可以!</p> <p>你可以放一段文字,也可以放一些表单,或者是一些图片。</p> </div> </modal-dialog>

现在看到的对话框是没有底部的,只有标题和主体内容。

View Demo

分分钟玩转Vue.js组件(二)

多个slot同时使用的场景还有很多,例如:用户的注册、登录、找回密码等这些表单集合,也可以用一个组件来完成。

父子组件之间的访问

有时候我们需要父组件访问子组件,子组件访问父组件,或者是子组件访问根组件。
针对这几种情况,Vue.js都提供了相应的API:

父组件访问子组件:使用$children或$refs

子组件访问父组件:使用$parent

子组件访问根组件:使用$root

$children示例

下面这段代码定义了3个组件:父组件parent-component,两个子组件child-component1和child-component2。

在父组件中,通过this.$children可以访问子组件。
this.$children是一个数组,它包含所有子组件的实例。

<div> <parent-component></parent-component> </div> <template> <child-component1></child-component1> <child-component2></child-component2> <button v-on:click="showChildComponentData">显示子组件的数据</button> </template> <template> <h2>This is child component 1</h2> </template> <template> <h2>This is child component 2</h2> </template> <script src="https://www.jb51.net/js/vue.js"></script> <script> Vue.component('parent-component', { template: '#parent-component', components: { 'child-component1': { template: '#child-component1', data: function() { return { msg: 'child component 111111' } } }, 'child-component2': { template: '#child-component2', data: function() { return { msg: 'child component 222222' } } } }, methods: { showChildComponentData: function() { for (var i = 0; i < this.$children.length; i++) { alert(this.$children[i].msg) } } } }) new Vue({ el: '#app' }) </script>

View Demo

分分钟玩转Vue.js组件(二)

$refs示例

组件个数较多时,我们难以记住各个组件的顺序和位置,通过序号访问子组件不是很方便。
在子组件上使用v-ref指令,可以给子组件指定一个索引ID:

<template> <child-component1 v-ref:cc1></child-component1> <child-component2 v-ref:cc2></child-component2> <button v-on:click="showChildComponentData">显示子组件的数据</button> </template>

在父组件中,则通过$refs.索引ID访问子组件的实例:

showChildComponentData: function() { alert(this.$refs.cc1.msg); alert(this.$refs.cc2.msg); }

$parent示例

下面这段代码定义了两个组件:child-component和它的父组件parent-component。
在子组件中,通过this.$parent可以访问到父组件的实例。

<div> <parent-component></parent-component> </div> <template> <child-component></child-component> </template> <template> <h2>This is a child component</h2> <button v-on:click="showParentComponentData">显示父组件的数据</button> </template> <script src="https://www.jb51.net/js/vue.js"></script> <script> Vue.component('parent-component', { template: '#parent-component', components: { 'child-component': { template: '#child-component', methods: { showParentComponentData: function() { alert(this.$parent.msg) } } } }, data: function() { return { msg: 'parent component message' } } }) new Vue({ el: '#app' }) </script>

View Demo

分分钟玩转Vue.js组件(二)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzzps.html