子向父方式1:通过props,如例子中子组件test1.vue向父组件App.vue传值
App.vue代码
<template> <div id="app"> <test1 :parfn="parfn"></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, components: {test1}, methods: { parfn: function (a) { alert(a) } } } </script>
test1.vue代码
<template> <div>i am test1</div> </template> <script> export default { data () { return { msg: ‘test1‘ } }, props: { parfn: { type: Function } }, created: function () { this.parfn(this.msg) } } </script>
效果图
子向父方式2:通过$parent
App.vue代码:
<template> <div id="app"> <test1></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, components: {test1}, methods: { parfn: function (a) { alert(a) } } } </script>
test1.vue代码:
<template> <div>i am test1</div> </template> <script> export default { data () { return { msg: ‘test1‘ } }, created: function () { this.$parent.parfn(this.msg) } } </script>
效果图:
子向父方式3:通过emit
App.vue代码
<template> <div id="app"> <test1 @myfn="parfn"></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, components: {test1}, methods: { parfn: function (a) { alert(a) } } } </script>
test1.vue代码:
<template> <div>i am test1</div> </template> <script> export default { data () { return { msg: ‘test1‘ } }, mounted: function () { this.$emit(‘myfn‘, this.msg) } } </script>
效果图:
父向子传值方式1:通过props
App.vue代码:
<template> <div id="app"> <test1 :msg="msg"></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, components: {test1} } </script>
test1.vue代码:
<template> <div>i am test1</div> </template> <script> export default { props: [‘msg‘], created: function () { alert(this.msg) } } </script>
效果图:
父向子方式2:通过$children
App.vue代码:
<template> <div id="app"> <test1></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, mounted: function () { this.$children[0].childfn(this.msg) }, components: {test1} }
test1.vue代码
<template> <div>i am test1</div> </template> <script> export default { methods: { childfn: function (a) { alert(a) } } } </script>
效果图:
父向子方式3:通过ref
App.vue代码:
<template> <div id="app"> <test1 ref="mychild"></test1> </div> </template> <script> import test1 from ‘@/components/test1.vue‘ export default { name: ‘App‘, data () { return { msg: ‘parent‘ } }, mounted: function () { this.$refs.mychild.childfn(this.msg) }, components: {test1} } </script>
test1.vue代码:
<template> <div>i am test1</div> </template> <script> export default { methods: { childfn: function (a) { alert(a) } } } </script>
效果图:
原文地址:https://www.cnblogs.com/hesj/p/10568869.html
时间: 2024-10-31 04:15:42