vue中组件传值

子组件给父组件传值

  1. 利用props来实现, 通过父组件给子组件传自定义的事件, 子组件通过props来接收这个自定义事件, 然后子组件调用这个传过来的事件

这里是父组件

   <Student :student1="studentHandfler" ref="styu"></Student>
   <script>
       import Student from './components/Student'
      export default {
        name: 'App',
        components: {
          Student
       },
  
  methods: {
    studentHandfler (data) {
      console.log("父组件给子组件传值", data)
    }
  },
}
</script>

这里是子组件

<template>
  <div class="Student">
    <h1>student</h1>
    <div>{{ student }}</div>
    <div> {{  age }}</div>
    <button @click="clickHandler">子组件给父组件传值</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      student: 'zs',
      age: 20
    }
  },
  props: ['student1'],
  methods: {
    clickHandler () {
    // 这边传值给父组件
      this.student1(this.student)
    }
  },
}
</script>
<style scoped>
</style>

第二种实现方式: 通过绑定自定义事件的形式来实现。子组件给父组件传值的目的

这里是父组件

<School ref="school1" 
    :schoolAddress="schoolAddress"
    :school="school"
    :num="num"
    @add="add"
    v-on:abc="abc"/>
 <script>
import School from './components/School'
export default {
  name: 'App',
  components: {
    School
  },
  mounted() {
    
    setTimeout(()=> {
 

 this.$refs.school1.$on('abc', this.abc)
    }, 1000)
  },
  data () {
    return {
      msg: 'Hello world',
      msg1: '',
      schoolAddress: '北京',
      school: '北京大学',
      num: 10,
      todo: [
      { id: '001', todo: false, name: '吃蛋' },
      { id: '002', todo: false, name: '睡觉' },
      { id: '003', todo: true, name: '睡觉2456' }
    ]
    }
  },
  methods: {
    abc (data) {
      console.log("父组件的abc的方法。。。", data)
    }
   
  }
}
</script>

这里是子组件

    <button @click="emitAbc">触发abc事件</button>
    methods: {
      emitAbc () {
         this.$emit("abc", this.school)
      }
  },

第三种实现方式通过ref来实现这个传值的目的
这里是父组件

<School ref="school1" 
    :schoolAddress="schoolAddress"
    :school="school"
    :num="num"
    @add="add"
  />
 <script>
import School from './components/School'
export default {
  name: 'App',
  components: {
    School
  },
  mounted() {
    
    setTimeout(()=> {
      this.$refs.school1.$on('abc', this.abc)
    }, 1000)
  },
  data () {
    return {
      msg: 'Hello world',
      msg1: '',
      schoolAddress: '北京',
      school: '北京大学',
      num: 10,
      todo: [
      { id: '001', todo: false, name: '吃蛋' },
      { id: '002', todo: false, name: '睡觉' },
      { id: '003', todo: true, name: '睡觉2456' }
    ]
    }
  },
  methods: {
    abc (data) {
      console.log("父组件的abc的方法。。。", data)
    }
   
  }
}
</script>

这里是子组件

   <button @click="emitAbc">触发abc事件</button>
    methods: {
      emitAbc () {
         this.$emit("abc", this.school)
      }
  },

第三种方式比较灵活些, 可以实现3s后传值的功能,

 this.$refs.school1.$on('abc', this.abc) 触发事件
  this.$refs.school1.$once('abc', this.abc)只触发一次的事件

你可能感兴趣的:(vue中组件传值)