[英]vue js passing data to child component
I have a child component contactView
of the component contacts-list
, which itself is a child.我有一个组件
contacts-list
的子组件contactView
,它本身就是一个子组件。 The problem is that I can not dynamically change the contents of this component问题是我不能动态改变这个组件的内容
html html
<div id="wrapper">
<component :is="currentView" keep-alive></component>
</div>
js 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'}]
})
After clicking on the button, the component does not display the changed data.单击按钮后,组件不显示更改的数据。 How can I do this correctly?
我怎样才能正确地做到这一点?
Vue cannot detect when you add properties to an object dynamically. Vue 无法检测到您何时向对象动态添加属性。 In this code,
在这段代码中,
app.accounts = [{name: 'hello', id: 1}];
You are adding the accounts
property to the Vue dynamically.您正在将
accounts
属性动态添加到 Vue。 Instead, start with an empty array.相反,从一个空数组开始。
data: {
contacts: [],
currentView: 'index-page',
accounts: []
}
Also in this code,同样在这段代码中,
$(document).on("click", "button.trig", function(){
alert('triggered');
app.accounts[0].contacts = [{email: '123@ya.ru'}]
})
you are adding the contacts
property to an object that did not previously have a contacts
property.您正在将
contacts
属性添加到以前没有contacts
属性的对象。 If you change your code to this it will work.如果您将代码更改为此它将起作用。
$(document).on("click", "button.trig", function(){
alert('triggered');
Vue.set(app.accounts[0],'contacts',[{email: '123@ya.ru'}])
})
I'm not sure why you are choosing to use jQuery to make these changes to your data, set the handler for your button, etc. All of these can be done with Vue.我不确定您为什么选择使用 jQuery 对数据进行这些更改,为您的按钮设置处理程序等。所有这些都可以使用 Vue 完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.