Vue Js获取数据onclick并附加在一个模态中

时间:2018-05-25 03:50:12

标签: dom vue.js vuejs2 append

我有两个组件,一个是父组件,另一个是子组件,它是一个模态弹出窗口。

父组件

<parent-component>

      <!-- this is a modal popup -->
      <child-component v-bind:message="childMessage"></child-component>

      <a href="#" @click="openModal(5)">Open model</a>

</parent-component>
<script>
   export default {
      data: function() {
        return {
           childMessage:{}
        }
      },
      methods:{
       openModal: function(id){
            axios.get('api/message/'+id)
                .then(response => {
                    this.childMessage = response.data;
                })
                .catch(error => {
                    console.log(error);
            })
            this.showModal = true
        }
     }
   }
</script>

子组件

<!-- this is a popup modal -->
<child-component>
    <h1>{{ message.title }}</h1>
</child-component>
<script>
   export default {
  props:{
    message: {},
  }
</script>

在父组件中,我触发模态并同时请求ajax。 我可以正确地将ajax数据传递给子组件。

但如果我打开控制台,则会出现错误

无法读取未定义的属性“标题”

(虽然我可以看到数据工作正常并且它已经在html页面中)

似乎附加数据{{ childMessage.title }}首先运行(在ajax请求之前)。

1 - 如何在ajax请求之后正确附加数据。

2 - 我是否需要检查未定义值的条件?

2 个答案:

答案 0 :(得分:0)

在这种情况下,您必须检查undefined值的条件,因为在message API调用结束之前正在呈现子组件。你可以这样做,

<child-component>
    <h1 v-if = "message">{{ message.title }}</h1>
</child-component>

答案 1 :(得分:0)

我没有看到您使用showModal的位置,但我认为这是一种显示或不显示child-component的切换。如果是这种情况,则错误可能来自于在调用API之后将showModal设置为true的事实。但是这个调用是异步的,您应该在this.showModal = true下的成功回调中移动this.childMessage = response.data;。 如果这样做,消息prop将在呈现子组件时初始化。

另外要注意你的道具类型,因为@ittus提到message似乎是一个字符串,根据child-component中的默认值,但你像模板中的对象一样使用它。