我有一个组件contactView
的子组件contacts-list
,它本身就是一个孩子。问题是我无法动态更改此组件的内容
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: '123@ya.ru'}]
})
单击按钮后,组件不会显示已更改的数据。我怎么能正确地做到这一点?
答案 0 :(得分: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: '123@ya.ru'}]
})
您要将contacts
属性添加到之前没有contacts
属性的对象中。如果您将代码更改为此代码,则可以正常工作。
$(document).on("click", "button.trig", function(){
alert('triggered');
Vue.set(app.accounts[0],'contacts',[{email: '123@ya.ru'}])
})
我不确定您为什么选择使用jQuery对数据进行这些更改,为按钮设置处理程序等等。所有这些都可以通过Vue完成。