【问题标题】:How can I add remote json data to prop?如何将远程 json 数据添加到道具?
【发布时间】:2019-08-29 10:05:10
【问题描述】:

下面的代码从远程服务获取 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>

【问题讨论】:

    标签: javascript vue.js prop


    【解决方案1】:

    因此,从这段代码中,如果您需要从“创建”钩子上的 API 获取数据,有三种可能的解决方案,

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

    1. 如果你真的需要物品作为道具,你应该在这个组件的父组件中进行这个API调用,然后在物品道具中传递响应数据

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

      items = newData" />

    在这个组件内部

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

    【讨论】:

    • 谢谢,我稍微调整了一下,但从你建议的解决方案中得到了解决。
    猜你喜欢
    • 2017-01-09
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多