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