2017-06-26 140 views
0

我有一个组件contacts-list的子组件contactView,它本身就是一个子组件。的问题是,我不能动态地改变该组件的内容vue js将数据传递给子组件

HTML

<div id="wrapper"> 
    <component :is="currentView" keep-alive></component> 
</div> 

JS

var IndexPage = Vue.component('index-page', { 
    template: '<div>Welcome to index page</div>' 
}) 

var Contact = Vue.component('contactView', { 
    template: ` 
    <div class="person-info"> 
    <ul v-for="contact in contacts"> 
     <span>here</span> 
     <li v-if="contact.email"> 
     <div class="icon icon-mail"></div> 
     {{contact.email}} 
     </li> 
    </ul> 
    </div> 
    `, 
    props: ['contacts'] 
}) 

var ContactsList = Vue.component('contacts-list', { 
    template: ` 
    <div id="list"> 
    list 
    <div v-for="item in items"> 
     <div class="person"> 
      person 
      <span class="name">{{item.name}}</span> 
      <button class="trig">Show {{item.id}}</button> 
     </div> 
     <contact-view :contacts="item.contacts"> </contact-view> 
    </div> 
    </div>`, 
    computed: { 
    items: function(){ 
     return this.$parent.accounts 
    } 
    }, 
    components: { 
    'contact-view': Contact 
    } 
}) 


var app = new Vue({ 
    el: '#wrapper', 
    data: { 
    contacts: [], 
    currentView: 'index-page' 
    } 
}) 

app.currentView = 'contacts-list'; 
app.accounts = [{name: 'hello', id: 1}]; 

$(document).on("click", "button.trig", function(){ 
    alert('triggered'); 
    app.accounts[0].contacts = [{email: '[email protected]'}] 
}) 

点击按钮后,该组件不显示改变了数据。我怎样才能正确地做到这一点?

回答

1

Vue cannot detect当您将属性动态添加到对象时。在这段代码中,

app.accounts = [{name: 'hello', id: 1}]; 

要动态添加accounts属性的Vue公司。相反,从一个空数组开始。

data: { 
    contacts: [], 
    currentView: 'index-page', 
    accounts: [] 
} 
在这段代码

此外,

$(document).on("click", "button.trig", function(){ 
    alert('triggered'); 
    app.accounts[0].contacts = [{email: '[email protected]'}] 
}) 

要添加contacts属性的对象,以前没有一个contacts财产。如果你改变你的代码,它会起作用。

$(document).on("click", "button.trig", function(){ 
    alert('triggered'); 
    Vue.set(app.accounts[0],'contacts',[{email: '[email protected]'}]) 
}) 

我不知道为什么你选择使用jQuery来进行这些更改您的数据,设置处理您的按钮等,所有这些都可以与Vue公司来完成。

+0

JQuery只是一个例子。你提出的方法不适合我,https://jsfiddle.net/mcfpgkyo/3/ –

+1

@ Marsel.V你也在动态地添加'accounts'。我更新了答案。 https://jsfiddle.net/mcfpgkyo/4/ – Bert