首页 > 解决方案 > 我想要简单的数组而不是 [__ob__: Observer]

问题描述

我调用 api 来获取数据,我用邮递员测试它,laravel 将它作为一个数组正确发送,但是 vue 将我的数组变成 [ ob : Observer] 并且我无法从中提取我的数组,这要归功于@Stockafisso 它已经解决了但

编辑:现在我的问题是,programming_languages 数组只能在 getLanguages() 方法中访问,不能在其他任何地方访问

 data(){
        return{
             answer: '',
             maxWrong: '',
            programming_languages : []              
        }
    },

    methods:{

        getLanguages(){
            axios.get('/api/toController').then((response)=> { 
  this.programming_languages = JSON.parse(JSON.stringify(response.data)); //works fine

this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name; //works fine
          this.maxWrong = this.answer.length;// works fine here, i dont want to initiaize answer variable in this method
                  
        
            });
        },

randWord(){
        this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;// it is not working here
//Error in created hook: "TypeError: Cannot read property 'name' of undefined"
            this.maxWrong = this.answer.length;// doesn't work here
          
        }

    },
    created(){
           this.getLanguages();
           this.randWord();
    }

我能做些什么?谢谢你

标签: laravelvue.jsvue-reactivity

解决方案


最有可能的错误在这里: this.programming_languages.push(JSON.parse(JSON.stringify(response.data)));

您正在将 Laravel 返回的数组插入到声明的programming_languages中,而您应该覆盖或连接它。为了更好地解释,一个小例子:

考虑一下:

let arr1 = [];
let arr2 = [1,2,3];

如果你这样做,arr1.push(arr2)你的 arr1 会[[1,2,3]]在你想要的时候出现[1,2,3]

回到你的问题,要解决它,你有两种方法:

一种)

.then((response)=> { 
                 this.programming_languages = JSON.parse(JSON.stringify(response.data));

b)

.then((response)=> { 
let swapArray = [...this.programming_languages];
this.programming_languages = swapArray.concat(JSON.parse(JSON.stringify(response.data)));

如果这不能解决错误,则问题可能出在 Laravel 返回的数组中。如果它没有数字或未排序的键,JS 将用 Ob“填充”缺失的空格。观察者试图保留密钥。


推荐阅读