问题:

vue项目中,如何将后台请求回来的数据,传递给子组件呢?

思路

此时肯定会想到v-bind自定义属性传值,子组件props来接收,但是很可惜,如果只是按照普通的父传子做法来做,最后的结果是子组件拿到数据的初始值,并没有拿到数据,然后报错 invalid prop

原因

原因很简单,还没有等到父组件赋值给它就已经把data里面这个自定义属性所绑定的初始值传过去了,
就是下面代码中的article,没有等到后台数据赋值article就把data里的article(null)传过去了。

代码实现

父组件

<template>
		......		
      <template slot-scope="scope">
      <el-button type="text" @click="hPreview(scope.row.articleBody)">预览</el-button>
       </template>
		......
    <!-- 预览弹框 子组件 -->
    <el-dialog
      width="60%"
      title="预览文章"
      :visible.sync="showDialog"
      append-to-body>
      <articles-preview :content = "article" v-if="article&&articleFlag"/>
    </el-dialog>
  </div>
</template>

<script>
import articlesPreview from '../components/articles-preview.vue'

export default {
  components: { articlesPreview },
  data () {
    return {
      article: null,
      articleFlag: false,
      showDialog: false,
    }
  },
  methods: {
    // 当点击了预览
    hPreview (art) {
      this.article = art
      // console.log(this.article)
      this.articleFlag = true
      this.showDialog = true
    }

子组件

<template>
  <div class='container'>
    <div v-html="content">
    </div>

  </div>
</template>

<script>
export default {
  props: {
    content: {
      type: String,
      required: true
    }
  }
}
</script>

<style scoped lang='less'></style>

点睛之笔

在这里插入图片描述在这里插入图片描述
这里使用v-if做了一个判断,当有article并且标记articleFlag为true的时候,子组件才存在并且传值过去。(articleFlag为true就说明后台请求的数据已经赋值给了article),如果不使用v-if,子组件props接到的result就是初始值并没有数据

Logo

前往低代码交流专区

更多推荐