Vue使用props父子组件传递数据
栏目: JavaScript · 发布时间: 6年前
内容简介:父组件子组件父组件
父组件
<template>
<div>
<demo :msg='msgData' :math = 'mathData' ></demo>
</div>
</template>
<script>
import Demo from './Demo.vue'
export default {
data () {
return {
msgData:'从父组件接收来的数据',
mathData : 2
}
},
components : {
Demo
}
}
</script>
子组件
<template>
<div>
<p>{{msg}}</p>
<p>{{math}}</p>
</div>
</template>
<script>
export default {
name: 'demo',
props: [ 'msg' , 'math'],
}
</script>
父子组件传递函数
父组件
<template>
<div>
<demo :fn = 'myFunction' ></demo>
</div>
</template>
<script>
import Demo from './Demo.vue'
export default {
components : {
Demo
},
methods: {
myFunction () {
console.log('vue')
}
}
}
</script>
子组件
<template>
<div>
<button @click='fn'>按钮</button>
</div>
</template>
<script>
export default {
name: 'demo',
props: [ 'fn' ],
}
</script>
另外,当传递的数量一旦多到已经让原子化不再结构清晰的时候,通过一个对象传递显得更为简洁明了。
父子组件传递对象数据
父组件
<template>
<div>
<demo v-bind= 'msg' ></demo>
</div>
</template>
<script>
import Demo from './Demo.vue'
export default {
components : {
Demo
},
data () {
return {
msg : {a:1,b:2}
}
}
}
</script>
子组件
<template>
<div>
<button>按钮</button>
</div>
</template>
<script>
export default {
name: 'demo',
props: ['a','b'],
created () {
console.log(this.a)
console.log(this.b)
},
}
</script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。