VUE中,子组件是不能直接访问父组件的数据(一般来说,当然如果你要破坏原则也是可以),如下<

<body>
  <div id="fathercomponent">
<ul>
<li v-for="item in fatherdatas">{{item}}</li> <!--父组件可以访问它自己的数据-->
</ul>
<child-component></child-component>
</div>
</body>
<script type="text/javascript">
Vue.component('child-component', {
// template:'<ul><li v-for="item in fatherdatas"></li></ul>'//子组件不能访问到父组件的数据
})
vm = new Vue({
data: {
fatherdatas: [1,2,3,4,5]
}
}).$mount('#fathercomponent');
</script>

上面代码  vm实例挂在了id 为fathercomponent 的DIV中,相当于fathercomponent为一个组件了,这个时候我们在其中定义了一个另一个新组件,这个新定义的组件,和原来的组件,即为父子关系,暂且命名为child-component

我们在vm 中定义的数据 fatherdatas,是父组件fathercomponent中的数据,可以直接在父组件中引用,子组件内部是无法访问到fatherdatas数据的。如果我们需要访问这个fatherdatas需要通过props属性来实现,具体如下

    <div id="fathercomponent">
<ul>
<li v-for="item in fatherdatas">{{item}}</li> <!--正确父组件可以访问它自己的数据-->
</ul>
<child-component :dataarr="fatherdatas"></child-component> <!--我们将父组件中的fatherdatas数据传给子组件中的dataarr-->
</div>
  Vue.component('child-component', {
props: ['dataarr'],//给props添加一个属性,这个属性名字是之前在组件标签中加的
template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>' //这个时候父组件中的fatherdatas 已经传递给了当前组件的dataarr,这样就可以访问了 })
vm = new Vue({
data: {
fatherdatas: [1,2,3,4,5]
}
}).$mount('#fathercomponent');

父组件传递给子组件,是按值传递,因为此时的值是一个对象地址,所以不管是改子组件中的dataarr,还是改父组件fatherdatas,都会影响到另一方,如下

    <div id="fathercomponent">
<ul>
<li v-for="item in fatherdatas">{{item}}</li> <!--正确父组件可以访问它自己的数据-->
</ul>
<child-component :dataarr="fatherdatas" @father="getfatherdatas"></child-component> <!--我们将父组件中的fatherdatas数据传给子组件中的dataarr-->
</div> <!--定义一个father事件-->
        Vue.component('child-component', {
props: ['dataarr'],//给props添加一个属性,这个属性名字是之前在组件标签中加的
template: '<ul><li v-for="item in dataarr">{{item}}</li></ul>', //这个时候父组件中的fatherdatas 已经传递给了当前组件的dataarr,这样就可以访问了
created: function () {
this.dataarr.push(6);//子组件中的dataarr 添加一个数组元素
this.$emit('father');//触发组件的father事件
} })
vm = new Vue({
methods: {
getfatherdatas() {
console.log(this.fatherdatas.join(','));//输出1,2,3,4,5,6
}
},
data: {
fatherdatas: [1,2,3,4,5]
}
}).$mount('#fathercomponent');

最新文章

  1. 分数try catch
  2. 使用supervisor提高nodejs调试效率 (已验证)
  3. C++:静态成员
  4. .NET和JSON
  5. GitLib
  6. A Byte of Python 笔记(12)python 标准库:sys、os,更多内容
  7. javascript 判断IOS版本号
  8. HBase总结(二十)HBase经常使用shell命令具体说明
  9. Exchange无法发送邮件 未找到匹配的连接器来路由外部收件人解决办法
  10. idea基本使用1
  11. eclipse修改android项目的apk包名类名
  12. 收藏:win32 控件之 sysLink控件(超链接)
  13. Navigation包中的move_base和amcl实现自动驾驶
  14. Linux 小记 — Ubuntu 自动化配置
  15. eclipse如何加入第三方jar包
  16. HDU 4557 Tree(可持久化字典树 + LCA)
  17. js-倒计时应用
  18. 优化dedecms设置文章url自定义规则
  19. postgresql-数据库网络地址存储探索
  20. Oracle安装后出现的问题

热门文章

  1. python使用类作为装饰器
  2. BearSkill纯代码搭建iOS界面
  3. Nginx Session Sticky
  4. atom中vue高亮支持emmet语法
  5. gem install cocoapods ERROR: While executing gem ... (Gem::FilePermissionError)
  6. win10禁止更新的方法
  7. hive-数据模型
  8. Java 数据库访问层
  9. windowsError错误码详解
  10. Englis - 英文字母和音标