第一:传递string、number等基本数据类型:
在构建vue项目中,props是子组件获取父组件的一种形式;在子组件中不可修改父组件传递的参数,代码以下:
一、父组件代码:html
<template> <div class="hello"> <childComponent @touchParentFuc="touchParentFuc" :fatherPassChild="fatherPassChild"></childComponent> </div> </template> <script> import childComponent from './childComponent' export default { name: 'HelloWorld', components: { childComponent }, data () { return { msg: 'Welcome to Your Vue.js App', fatherPassChild: '父传子' } }, methods: { touchParentFuc () { console.log(this.fatherPassChild) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
2子组件代码:vue
<template> <div class="hello"> <div>这是子组件</div> <div>这是父组件的值:{{fatherPassChild}}</div> </div> </template> <script> export default { name: 'HelloWorld', props: ['fatherPassChild'], created () { this.touchParentFuc() }, data () { return { msg: 'Welcome to Your Vue.js App' } }, methods: { touchParentFuc () { this.fatherPassChild = '888' this.$emit('touchParentFuc') } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
注释:
页面展现子组件修改后的值:
“这是子组件
这是父组件的值:888”;
在子组件中,尝试修改父组件传递过来的值,此时chrome控制台会报错:[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "fatherPassChild"
;
同时,父组件中,打印的字段为修改以前的字段:
父传子 。
chrome
第二:传递数组、对象等引用型数据类型:
若是经过props传递引用数据类型,在子组件中改修父组件的属性值,会出现什么状况?撸码以下:
一、父组件代码:数组
<template> <div class="hello"> <childComponent @touchParentFuc="touchParentFuc" :fatherPassChild="fatherPassChild"></childComponent> </div> </template> <script> import childComponent from './childComponent' export default { name: 'HelloWorld', components: { childComponent }, data () { return { msg: 'Welcome to Your Vue.js App', fatherPassChild: { objData: 'my is object' } } }, methods: { touchParentFuc () { console.log(this.fatherPassChild) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
2子组件代码:ide
<template> <div class="hello"> <div>这是子组件</div> <div>这是父组件的值:{{fatherPassChild.objData}}</div> </div> </template> <script> export default { name: 'HelloWorld', props: ['fatherPassChild'], created () { this.touchParentFuc() }, data () { return { msg: 'Welcome to Your Vue.js App' } }, methods: { touchParentFuc () { this.fatherPassChild.objData = 'object is my' this.$emit('touchParentFuc') } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
注释:
此时,页面展现的内容是子组件修改后;同时,控制台并无报错;why?ui
按照官网的解释:
注意在 JavaScript 中对象和数组是经过引用传入的,因此对于一个数组或对象类型的 prop 来讲,在子组件中改变这个对象或数组自己将会影响到父组件的状态。this
简单总结:一、在使用props传递数据的过程当中,若是传递的是基本数据类型,则在子组件中不能修改父组件传递过来的值,此时符合cue的单向数据流方式;
二、若是传递的是引用型数据类型,则此时能够在子组件操做父组件传递过来的值,此时数据能够双向通讯,违背单向数据流方式。code
我的理解,props传递参数不一样,影响子组件是否能更改父组件props传递的值;跟const声明变量相似。component