简体   繁体   中英

vue js passing data to child component

I have a child component contactView of the component contacts-list , which itself is a child. The problem is that I can not dynamically change the contents of this component

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

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. In this code,

app.accounts = [{name: 'hello', id: 1}];

You are adding the accounts property to the Vue dynamically. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM