記如何解決vue父組件改變不了子組件props傳過來的數組

父組件:(組件內容寫個大概)數組

<template>
  <div class="feedback">
    <comment-item :commentList="commenList"></comment-list>
  </div>
</template>

<script>
import CommentItem from '...' //導入子組件
import {queryFeedBack} from '...'  //導入數據接口

export default {
  data() {
     return {
       commentList: []
    }
  },
  mounted() {
   queryFeedBack(查詢條件),then(res => {
     this.commentList = res.page.list
   })
  }
}
</script>複製代碼

子組件CommentItem(組件寫個大概)bash

<template>
   <ul>
     <li v-for="item in dataset">  //dataset是loadsh處理過的數據
       <div class="right-panel">
         <el-button @click="(item.showPanel = !item.showPanel)">我來回復:</el-button>
          <!--點擊我來回復:點擊一次顯示,再點擊一次不顯示-->
         <div v-show="item.showPanel">  這個showpanel是在父組件裏面新加的屬性
           <input  v-model="item.replyText">
           <button @click="submitReply(item)">提交回復</button>
         </div>
       </div>
     </li>
   </ul>
</template>

<script>
import _ from 'loadsh' //導入的這個工具我作了一會功課,裏面封裝了不少字符串、數組、對象等常見數據類型的處理函數
// lodash的全部函數都不會在原有的數據上進行操做,而是複製出一個新的數據而不改變原有數據,下面須要仔細去看一下這個工具的使用。

export default {
  props: {
    commentList: {
      type: Array,
      default() {
         []
        }
     }
   },
   data() {
     return {
       dataset: []  //複製了個數組來處理
      }
     },
   watch: {  //這裏是重點,用到了loadsh處理函數
    commentList: {
     immediate: true,
     handler(value) {   //好好理解下面這句處理
       this.dataset = _.map(value || [],item => _.extend({showPanel:false,replyText: null}, item))
     }
    }
   },
methods: {
  submitReply(data) {  
    data.replyText = null   //提交完文本框須要清空
  }
}
 }
</script>複製代碼

總結:函數

必定要了解loadsh工具箱怎麼用,數組寫在props裏面,數組的值在父組件中很難被改變,須要藉助loadsh工具箱在子組件中進行處理。工具

相關文章
相關標籤/搜索