vue - 通过组件数组添加时属性不响应

嘿我的代码看起来像这样:


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它们是反应性的。但我需要在我的项目中循环传递它们。有任何想法吗?


郎朗坤
浏览 116回答 1
1回答

慕码人2483693

除非您像这样定义数据,否则它会起作用:data() {&nbsp; return {&nbsp; &nbsp; cars: [ ... ],&nbsp; &nbsp; persons: [ ... ],&nbsp; &nbsp; componentData: [&nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.cars }, id: 1 },&nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.persons }, id: 2 },&nbsp; &nbsp; ]&nbsp; }}this.cars并且this.persons在您定义 时不可访问componentData。使用计算来维持反应性:new Vue({&nbsp; el: "#app",&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; cars: [ ... ],&nbsp; &nbsp; &nbsp; persons: [ ... ]&nbsp; &nbsp; }&nbsp; },&nbsp; computed: {&nbsp; &nbsp; componentData() {&nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.cars }, id: 1 },&nbsp; &nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.persons }, id: 2 },&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }&nbsp; }});编辑:这是一个演示const TestPane = {&nbsp; template: `&nbsp; &nbsp; <div class="pane">&nbsp; &nbsp; &nbsp; {{ data }}&nbsp; &nbsp; </div>&nbsp; `,&nbsp; props: ['data']}/***** APP *****/new Vue({&nbsp; el: "#app",&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; cars: ['honda', 'ferrari'],&nbsp; &nbsp; &nbsp; persons: ['Bob', 'Mary']&nbsp; &nbsp; }&nbsp; },&nbsp; computed: {&nbsp; &nbsp; componentData() {&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.cars }, id: 1 },&nbsp; &nbsp; &nbsp; &nbsp; { name: TestPane, props: { data: this.persons }, id: 2 },&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }&nbsp; }});.pane {&nbsp; padding: 12px;&nbsp; background: #dddddd;&nbsp; margin: 4px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app">&nbsp; <div v-for="component in componentData" :key="component.id">&nbsp; &nbsp; &nbsp;<component v-bind:is="component.name" v-bind="component.props">&nbsp; &nbsp; &nbsp;</component>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript