1、父组件获取子组件的数据和方法 $refs
子组件:
<template> <div class="header"> <h3>{{ zz }}</h3> </div></template> <script>export default { name: ‘cx‘, data () { return { zz: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXX‘ } }, methods: { zxx: function () { alert(‘子组件方法zxx()‘) } }}</script><style scoped></style> 父组件:
<template> <div> <h1>{{ mm }}</h1> <yyy ref="ry"></yyy> </div></template> <script>import yyy from ‘./cx‘ export default { name: ‘cy‘, data () { return { mm: ‘YYYYYYYYYYYYYYYYYYYYYYYYYYYY‘ } }, mounted () { alert(this.$refs.ry.zz) this.$refs.ry.zxx(‘父组件赋值的值‘) }, components: { yyy: yyy }}</script><style scoped></style> 2、子组件调父组件的数据 props子组件:
<template> <div class="header"> <h3>{{ zz }}</h3> <h1>{{ msg }}</h1> </div></template> <script>export default { name: ‘cx‘, data () { return { zz: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXX‘ } }, props: [‘msg‘], methods: { }}</script><style scoped></style>
父组件:
<template> <div> <h1>{{ mm }}</h1> <yyy :msg = "fav"></yyy> </div></template> <script>import yyy from ‘./cx‘ export default { name: ‘cy‘, data () { return { mm: ‘YYYYYYYYYYYYYYYYYYYYYYYYYYYY‘, fav: ‘父组件的数据‘ } }, mounted () { }, components: { yyy: yyy }}</script><style scoped></style>
3、子组件调用父组件的方法并传递数据 $emit
子组件:
<template> <div class="header"> <h3>{{ zz }}</h3> <button @click="cd">传递参数</button> </div></template> <script>export default { name: ‘cx‘, data () { return { zz: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXX‘ } }, methods: { cd: function (msg) { this.$emit(‘zbt‘,‘子组件传递的参数‘) } }}</script><style scoped></style>
父组件:
<template> <div> <h1>{{ mm }}</h1> <yyy type="button" @zbt = "bt">获取子组件传递的参数</yyy> </div></template> <script>import yyy from ‘./cx‘ export default { name: ‘cy‘, data () { return { mm: ‘YYYYYYYYYYYYYYYYYYYYYYYYYYYY‘ } }, methods: { bt: function (msg) { alert(msg) } }, components: { yyy: yyy }}</script><style scoped></style> 4、兄弟组件互相传值
原文地址:https://www.cnblogs.com/-llf/p/12195978.html
时间: 2024-10-11 13:06:51