我正在尝试在模态中循环和引用vue数据值,并且遇到一个错误,即尽管组件初始化中提供了值,但该字段需要是反应性的。知道为什么会这样吗?

小提琴:
https://jsfiddle.net/mwLbw11k/2618/

JS

// register modal component
Vue.component('modal', {
  template: '#modal-template'
})

// start app
new Vue({
  el: '#app',
  data: {
    myData: [{'first': 'Matt', 'last': 'Smith'}, {'first': 'Tom', 'last': 'Brady'}],
    showModal: false
  }
})


的HTML

<script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              <ul>
                <li v-for="user in myData"> {{ user.first }} {{ user.last }}</li>
              </ul>
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>

<!-- app -->
<div id="app">
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <!-- use the modal component, pass in the prop -->
  <modal v-if="showModal" @close="showModal = false">
  </modal>
</div>


Vue警告

[Vue warn]: Property or method "myData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

最佳答案

您应该将myData添加到modal组件道具

Vue.component('modal', {
  template: '#modal-template',
  props: ['myData']
})


然后像这样从父级传递它:

  <modal v-if="showModal" :my-data="myData" @close="showModal = false">
  </modal>

09-25 13:01