繁体   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