我有這個非常簡單的Vue JS頁面如下:Vue公司JS - 更新索引值不更新第二組件的視圖
<html>
<head>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="main-container">
<div id="contact-table">
<table>
<thead>
<tr>
<th>Contact Name</th>
<th>Email</th>
</tr>
</thead>
<tbody v-for="contact in contacts">
<tr v-on:click="selectContact(contact.index)">
<td>
{{contact.name}}
</td>
<td>
{{contact.email}}
</td>
</tr>
</tbody>
</table>
</div>
<div id="contact-form">
<input type="text" v-model="contactName"/>
<input type="text" v-model="contactEmail"/>
<button type="button" v-on:click="updateContact">Update Contact</button>
</div>
</div>
</body>
<script>
var hub = {
contacts: [
{
name: "James",
email: "[email protected]",
index: 0
},
{
name: "Mary",
email: "[email protected]",
index: 1
}
],
index: 0
};
var contactTable = new Vue({
el: "#contact-table",
data: {
contacts: hub.contacts
},
methods: {
selectContact: function(index) {
hub.index = index;
console.log(hub.index);
}
}
});
var contactForm = new Vue({
el: "#contact-form",
data: {
contactName: hub.contacts[hub.index].name,
contactEmail: hub.contacts[hub.index].email
},
methods: {
updateContact: function() {
hub.contacts[hub.index].name = this.contactName;
hub.contacts[hub.index].email = this.contactEmail;
}
}
});
</script>
</html>
基本上它包含兩個部分Vue公司 - 表和輸入表單。通過單擊表中的行,它應該更改輸入表單中的值,但單擊更新聯繫人按鈕它應更新表單詳細信息。
第二部分運行良好 - 但是,當我單擊表的行時,儘管console.log告訴我hub.index已更新,但輸入表單中的視圖不是。
我相信這應該是一個雙向綁定在這裏,所以我只是想知道我在哪裏做錯了。
聽起來像你可能想要實現[事件總線](https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication)或[狀態管理模式](https ://vuejs.org/v2/guide/state-management.html) – Phil