亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

vue - 通過組件數組添加時屬性不響應

vue - 通過組件數組添加時屬性不響應

郎朗坤 2023-08-05 11:04:05
嘿我的代碼看起來像這樣:componentData: [   { name: TestPane, props: { data: this.cars }, id: 1 },   { name: TestPane, props: { data: this.persons }, id: 2 },]<div v-for="component in componentData" :key="component.id">   <component v-bind:is="component.name" v-bind="component.props">   </component></div>props 不是反應性的。當我在沒有循環的情況下正常傳遞道具時,:data=cars它們是反應性的。但我需要在我的項目中循環傳遞它們。有任何想法嗎?
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

除非您像這樣定義數據,否則它會起作用:


data() {

  return {

    cars: [ ... ],

    persons: [ ... ],

    componentData: [

      { name: TestPane, props: { data: this.cars }, id: 1 },

      { name: TestPane, props: { data: this.persons }, id: 2 },

    ]

  }

}

this.cars并且this.persons在您定義 時不可訪問componentData。使用計算來維持反應性:


new Vue({

  el: "#app",

  data() {

    return {

      cars: [ ... ],

      persons: [ ... ]

    }

  },

  computed: {

    componentData() {

      return [

        { name: TestPane, props: { data: this.cars }, id: 1 },

        { name: TestPane, props: { data: this.persons }, id: 2 },

      ]

    }

  }

});

編輯:這是一個演示

const TestPane = {

  template: `

    <div class="pane">

      {{ data }}

    </div>

  `,

  props: ['data']

}


/***** APP *****/

new Vue({

  el: "#app",

  data() {

    return {

      cars: ['honda', 'ferrari'],

      persons: ['Bob', 'Mary']

    }

  },

  computed: {

    componentData() {

        return [

        { name: TestPane, props: { data: this.cars }, id: 1 },

        { name: TestPane, props: { data: this.persons }, id: 2 },

      ]

    }

  }

});

.pane {

  padding: 12px;

  background: #dddddd;

  margin: 4px;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

  <div v-for="component in componentData" :key="component.id">

     <component v-bind:is="component.name" v-bind="component.props">

     </component>

  </div>

</div>


查看完整回答
反對 回復 2023-08-05
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號