Vue 中父传子组件传值,开发项目中总会遇到这样或那样的坑,作为前端小白,每天都在填坑中度过。。。

第一种情况: 简单传值,子组件只负责显示;
父组件向子组件传递一个hello word; 子组件接收并显示出来;
父组件Father.vue

<template>
  <div id="app">
    <Child :msg = "message"/>
  </div>
</template>
<script>
import Child from './Child'

export default {
  name: 'App',
  data() {
    return {
      message: ""
    } 
  },
  components: {
    Child
  },
  mounted() {
    this.timer = setTimeout(() => {
      this.message = "hello world";
    }, 3000)  
  }
}
</script>

子组件Child.vue

<template>
  <div>
    {{msg}}
  </div>
</template>

<script>

export default {
  name: 'App',
  props: [
      "msg"
  ]
}
</script>

<style>

</style>

第二种情况:父组件向子组件传值,子组件接收传值并修改传值并显示到页面上;
我们可以使用watch 监听值的改变,当然我们也可以使用计算属性;
我们先来说第一种使用watch 监听:父组件不变;

子组件Child.vue

<template>
  <div>
    {{childMsg}}
  </div>
</template>

<script>

export default {
  name: 'App',
  props: [
      "msg"
  ],
  data() {
      return {
          childMsg: ""
      }
  },
  watch: {
      msg(newVal) {
          if(newVal !== "") {
              this.childMsg = newVal + "----child";
          }
      }
  }
}
</script>

<style>

</style>

说完了监听的,我们再来说一说计算属性的;父组件不变
子组件Child.vue

<template>
  <div>
    {{childMsg}}
  </div>
</template>

<script>

export default {
  name: 'App',
  props: [
      "msg"
  ],
  computed: {
      childMsg() {
          return this.msg + "----child";
      }
  }
}
</script>

<style>

</style>

当然我们可以给计算属性设置get,和set 方法,我在项目中就用到了这种方法,父组件传递给子组件一个对象,在子组件里接收这个对象,并修改这个对象;
父组件Father.vue

<template>
  <div id="app">
    <Child :value = "data"/>
  </div>
</template>
<script>
import Child from './Child'

export default {
  name: 'App',
  data() {
    return {
      data: null
    } 
  },
  components: {
    Child
  },
  mounted() {
    this.timer = setTimeout(() => {
      this.data = {
        "name": "south Joe",
        "age": 16,
      }
    }, 3000)  
  }
}
</script>

子组件Child.vue

<template>
  <div>
    {{message}}
    <button @click="handleModify">修改年龄,姓名</button>
  </div>
  
</template>

<script>

export default {
  name: 'App',
  props: [
      "value"
  ],
  computed: {
      message: {
        get: function() {

            if(this.value) {
                return [this.value.name,this.value.age]
            }
            
        },
        set: function(newValue) {
            this.value.name = newValue[0];
            this.value.age = newValue[1];
        }
      }
  },
  methods: {
      handleModify() {
          this.message = ["yangyang",17];
      }
  }
}
</script>

<style>

</style>

职场小白south Joe,望各位大神批评指正,祝大家学习愉快!

    原文作者:南乔
    原文地址: https://segmentfault.com/a/1190000018765314
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞