【问题标题】:TypeError: this.$set is not a function类型错误:this.$set 不是函数
【发布时间】:2016-01-06 12:36:21
【问题描述】:

您好,我收到此错误: Uncaught (in promise) TypeError: this.$set is not a function

这里是代码:

     export default {
        data: function() {
            return { movies: '' }
        },

        ready: function() {
            this.showMovies()
        },

        methods: {
            showMovies: function() {
                 this.$http.get(config.api.url + '/movies').then(function (response) {
                    this.$set('movies', response.data)
                 })
             }
        }
     }

【问题讨论】:

  • 解决者:this.$http.get(config.api.url + '/movies/geners', function(geners) { this.$set('geners', geners) })

标签: vue.js


【解决方案1】:

this.$set 在您的示例代码中不是函数的原因是this 不再引用 Vue ViewModel 实例。

要使您发布的代码正常工作,您需要保持对它的引用:

export default {
    data: function() {
        return { movies: '' }
    },

    ready: function() {
        this.showMovies()
    },

    methods: {
        showMovies: function() {
             var vm = this; // Keep reference to viewmodel object
             this.$http.get(config.api.url + '/movies').then(function (response) {
                vm.$set('movies', response.data)
             })
         }
    }
 }

【讨论】:

    【解决方案2】:

    在回调函数中你丢失了 Vue 实例 (this),这可以通过使用箭头函数 ()=>{...} 来解决:

       this.$http.get(config.api.url + '/movies').then((response)=> {
                        this.$set('movies', response.data)
                     })
    

    或将回调绑定到this

       this.$http.get(config.api.url + '/movies').then(function (response) {
                        this.$set('movies', response.data)
                     }).bind(this)
    

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 2023-03-05
      • 2018-11-07
      • 1970-01-01
      • 2019-07-18
      • 2020-10-06
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      相关资源
      最近更新 更多