前言
组件是 vue.js 最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用。如何传递数据也成了组件的重要知识点之一。
组件
组件与组件之间,还存在着不同的关系。父子关系与兄弟关系(不是父子的都暂称为兄弟吧)。
父子组件
父子关系即是组件 A 在它的模板中使用了组件 B,那么组件 A 就是父组件,组件 B 就是子组件。
// 注册一个子组件Vue.component('child', { data: function(){ text: '我是father的子组件!' } template: '<span>{{ text }}</span>'})// 注册一个父组件Vue.component('father', { template: '<div><child></child></div>' // 在模板中使用了child组件})
直接使用 father 组件的时候:
<div id="app"> <father></father></div>
页面中就会渲染出 :我是father的子组件!
father 组件在模板中使用了 child 组件,所以它就是父组件,child 组件被使用,所以 child 组件就是子组件。
兄弟组件
两个组件互不引用,则为兄弟组件。
Vue.component('brother1', { template: '<div>我是大哥</div>'})Vue.component('brother2', { template: '<div>我是小弟</div>'})
使用组件的时候:
<div id="app"> <brother1></brother1> <brother2></brother2></div>
页面中就会渲染出 :
我是大哥
我是小弟
Prop
子组件想要使用父组件的数据,我们需要通过子组件的 props 选项来获得父组件传过来的数据。以下我使用在 .vue 文件中的格式来写例子。
如何传递数据
在父组件 father.vue 中引用子组件 child.vue,把 name 的值传给 child 组件。
<template> <div class="app"> // message 定义在子组件的 props 中 <child :message="name"></child> </div></template><script> import child from './child.vue'; export default { components: { child }, data() { return { name: 'linxin' } } }</script>
在子组件 child.vue 中的 props 选项中声明它期待获得的数据
<template> <span>Hello {{message}}</span></template><script> export default { // 在 props 中声明获取父组件的数据通过 message 传过来 props: ['message'] }</script>
那么页面中就会渲染出:Hello linxin
单向数据流
当父组件的 name 发生改变,子组件也会自动地更新视图。但是在子组件中,我们不要去修改 prop。如果你必须要修改到这些数据,你可以使用以下方法:
新闻热点
疑难解答
图片精选