vue父组件与子组件之间的数据传递

父组件向子组件传递数据

父组件用数据绑定;子组件用props接收

<!-- test-vue-model父组件 -->
<template>
  <div>
    <model-son :datas="fatherData"></model-son>
  </div>
</template>
<script>
import ModelSon from 'views/test/test-vue-model-son'
export default{
  data() {
    return {
      fatherData: '父传子'
    }
  },
  components: {
    ModelSon
  }
}
</script>
<!-- test-vue-model-son  子组件 -->
<template>
  <div><span>子组件</span>{{datas}}</div>
</template>
<script>
export default{
  props: {
    datas: {
      type: String,
      default: ''
    }
  }
}
</script>

子组件向父组件传递参数通过事件发送

<!-- test-vue-model父组件 -->
<template>
  <div>
    <model-son :datas="fatherData" @receiveMe="handleMe"></model-son>
  </div>
</template>
<script>
import ModelSon from 'views/test/test-vue-model-son'
export default{
  data() {
    return {
      fatherData: '父传子'
    }
  },
  methods: {
    handleMe(item) {
      console.log('接收子元素item', item)
    }
  },
  components: {
    ModelSon
  }
}
</script>
<!-- test-vue-model-son  子组件 -->
<template>
  <div>
    <div><span>子组件</span>{{datas}}</div>
    <div @click="emitNewData()">向父组件发送事件</div>
  </div>
</template>
<script>
export default{
  props: {
    datas: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      new: '我的'
    }
  },
  methods: {
    emitNewData() {
      this.$emit('receiveMe', this.new)
    }
  }
}
</script>

绿色为:父传子路径

红色:子传父路径

posted @ 2018-03-23 18:01  海螺呜呜  阅读(555)  评论(0编辑  收藏  举报