父子组件之间的传值

你的名字 2023-06-20 11:58 101阅读 0赞

一、子组件向父组件传值

子组件通过this.$emit()的方式将值传递给父组件,父组件用函数的方式接收。
子组件:

  1. <template>
  2. <div class="app">
  3. <input @click="sendMsg" type="button" :value="msg">
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data () {
  9. return {
  10. msg: "我是子组件的msg", //将msg传递给父组件
  11. }
  12. },
  13. methods:{
  14. sendMsg(){
  15. //func: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
  16. this.$emit('func',this.msg)
  17. }
  18. }
  19. }
  20. </script>

注意:这里的func是父组件中绑定的函数名父子组件中命名要一致
父组件:

  1. <template>
  2. <div class="app">
  3. <child @func="getMsgFormSon"></child>
  4. </div>
  5. </template>
  6. <script>
  7. import child from './child.vue'
  8. export default {
  9. data () {
  10. return {
  11. msgFormSon: "this is msg"
  12. }
  13. },
  14. components:{
  15. child,
  16. },
  17. methods:{
  18. getMsgFormSon(data){
  19. this.msgFormSon = data //data为子组件传上来的数据
  20. console.log(this.msgFormSon)
  21. }
  22. }
  23. }
  24. </script>

总结一下:

子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性。抓准这两点对于父子通信就好理解了

二、父组件向子组件传值

父组件:

  1. <template>
  2. <div class="app">
  3. <child :msg="message"></child>
  4. </div>
  5. </template>
  6. <script>
  7. import child from './child.vue'
  8. export default {
  9. data () {
  10. return {
  11. message: "this is msg"
  12. }
  13. },
  14. components:{
  15. child,
  16. }
  17. }
  18. </script>

子组件

  1. <template>
  2. <div class="app">
  3. <h2>child子组件部分</h2>
  4. <p>{
  5. {message}}</p>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. props: {
  11. message:{
  12. type: String,
  13. default: ''
  14. },
  15. }
  16. }
  17. </script>

总结一下:

子组件在props中创建一个属性,用以接收父组件传过来的值
父组件中注册子组件
在子组件标签中添加子组件props中创建的属性
把需要传给子组件的值赋给该属性

三、父组件调用子组件的方法

通过ref
在DOM元素上使用 r e f s 可 以 迅 速 进 行 d o m 定 位 , 类 似 于 refs可以迅速进行dom定位,类似于 refs可以迅速进行dom定位,类似于(“selectId”)

使用this.$refs.paramsName能更快的获取操作子组件属性值或函数
子组件:

  1. methods:{
  2. childMethods() {
  3. alert("I am child's methods")
  4. }
  5. }

父组件
在子组件中加上ref即可通过this.$refs.method调用

  1. <template>
  2. <div @click="parentMethod">
  3. <children ref="c1"></children>
  4. </div>
  5. </template>
  6. <script>
  7. import children from 'components/children/children.vue'
  8. export default {
  9. data(){
  10. return {
  11. }
  12. },
  13. computed: {
  14. },
  15. components: {
  16. children
  17. },
  18. methods:{
  19. parentMethod() {
  20. console.log(this.$refs.c1) //返回的是一个vue对象,可以看到所有添加ref属性的元素
  21. this.$refs.c1.childMethods();
  22. }
  23. }
  24. }
  25. </script>

发表评论

表情:
评论列表 (有 0 条评论,101人围观)

还没有评论,来说两句吧...

相关阅读