20-vue组件传参(父传子,子传父)

父传子:

父组件向子组件传入一个参数,可以通过 props配置项,让组件接收外部传过来的数据

1)传递数据

这里需要注意,通过 age = "18"的方式,传递进去的数据是字符类型的,通过动态绑定 :age = "26" 的方式,传递进去的数据是整型类型

<!--这里需要注意,:age="26" 代表 v-bind动态绑定,传入的age是int类型-->
<Student name="马铃薯1" :sex="'男'" :age="26"></Student>

<!--这里的 age="18",传入的age是字符串类型-->
<Student name="马铃薯2" sex="男" age="18"></Student>

2)接收数据

第一种方式(只接收)

// props 配置项(开发过程中,用的比较多)
// 简单声明接收
props:["name","sex","age"],

第二种方式(限制类型)

// 接收的同时,对数据进行类型限制
props:{
    name:String,
        sex:String,
        age:Number,
},

 

父传子案例,父组件ClassView.vue,子组件ChildComponent.vue

子组件ChildComponent.vue

<template>
  <div>
    <h1> 子组件从父组件接收到的参数:{{ message }} </h1>
  </div>
</template>

<script>
export default {
  props: ['message']
}
</script>

父组件ClassView.vue

<template>
  <div>
    <h1>班级管理信息</h1>
    <ChildComponent :message="message" />
  </div>
</template>

<script>
import ChildComponent from '@/components/ChildComponent.vue'

export default{
  components: {
    ChildComponent
  },
  data() {
    return {
      message: '111'
    }
  }
}
</script>

<style>

</style>

 

 

子传父:

子组件向父组件传入一个参数,可以通过一个自定义事件向父组件传递参数

1)传递数据

通过一个自定义事件向父组件传递参数

//在子组件中的methods中写
methods:{
    this.$emit('passtofather', this.sonMsg)
}

2)接收数据

通过实现这个自定义事件来接收参数

// html
<son @passtofather="myfn" /> 
// 在父组件中接收参数时,如果代码写在 html 行内,要获取传入的数据可以通过 $event

// js
export default {
    methods: {
        myfn(value) {
            // value 就是子组件传入的参数
        }
    }
}

 

子传父案例,父组件ClassView.vue,子组件ChildComponent.vue

子组件ChildComponent.vue

<template>
  <div>
    <h1> 子组件从父组件接收到的参数:{{ message }} </h1>
  </div>
</template>

<script>
export default {
  props: ['message'],
  mounted() {
    this.info()
  },
  methods: {
    // 子传父,子组件通过this.$emit('info',data)传递数据给父组件
    info() {
      let data = 222;
      this.$emit("info", data);
      console.log("这是 ChildComponent 组件的info方法,传递参数",data)
    }
  }
}
</script>

父组件ClassView.vue

<template>
  <div>
    <h1>班级管理信息</h1>
    <ChildComponent @info="info" :message="message" />
    <h1>父组件从子组件接收到的参数:{{ receive }}</h1>
  </div>
</template>

<script>
import ChildComponent from '@/components/ChildComponent.vue'

export default{
  components: {
    ChildComponent
  },
  data() {
    return {
      message: '111',
      receive: ''
    }
  },
  methods:{
    info(data){
      this.receive = data
      console.log("这是ClassView组件的info方法,接收到的参数",data)
    }
  }
}
</script>

<style>

</style>

 

posted @ 2024-04-25 15:55  马铃薯1  阅读(9)  评论(0编辑  收藏  举报