動態

詳情 返回 返回

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,望各位大神批評指正,祝大家學習愉快!

Add a new 評論

Some HTML is okay.