如何将远程 json 数据添加到 prop?

How can I add remote json data to prop?

下面的代码从远程服务获取 JSON 数据并将其提供给一个变量,该变量稍后也应该将其提供给道具。 之后我操纵道具中的物品。 当然,我在尝试改变道具时得到了 Vue Error

代码如下:

<script>
import axios from 'axios'
import { API_BASE_URL } from '../config'

export default {
  props: {
    items: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  data() {
    return {
      isLoading: true,
      novels: [],
      search: "",
      isOpen: false,
      arrowCounter: 0
    }
  },
  created() {
    axios.get(API_BASE_URL + '/novels').then(response => {
      this.novels = response.data.data
    })
    // this.items = this.novels
    this.isLoading = false
  },
  methods: {
    getNovel(novel){
      this.$router.push({ path: `novel/${novel.id}`})
      // this.$router.go(1)
    },

    onChange(){
      // Let's warn the parent that a change was made
      this.$emit("input", this.search);

      // Let's search our flat array
      this.filterResults();
      this.isOpen = true
    },

    filterResults() {
      // first uncapitalize all the things
      this.novels = this.items.filter(item => {
        return item.toLowerCase().indexOf(this.search.toLowerCase()) > -1;
      });
    }
}
</script>

所以从这段代码来看,如果你需要在"Create"钩子上从API获取数据,有三种可能的解决方案,

  1. 您不应将项目定义为道具,而应定义为数据。

  1. 如果你真的需要 items 作为 prop,你应该 API 在这个组件的父级内部调用,然后在 items prop
  2. 中传递响应数据

  1. 使用此代码,您可以将方法传递给组件,此组件可以使用新数据发出该方法。并且 parent 中的那个方法可以更新 items 数组。示例如下

并在此组件内

created() {
    axios.get(API_BASE_URL + '/novels').then(response => {
      this.novels = response.data.data
    })
    this.$emit('apiResponse', this.novels)
    this.isLoading = false
  },