簡體   English   中英

vue js將數據傳遞給子組件

[英]vue js passing data to child component

我有一個組件contacts-list的子組件contactView ,它本身就是一個子組件。 問題是我不能動態改變這個組件的內容

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'}]
})

單擊按鈕后,組件不顯示更改的數據。 我怎樣才能正確地做到這一點?

Vue 無法檢測到您何時向對象動態添加屬性。 在這段代碼中,

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 完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM