【问题标题】:How do I pass data from a vue-resource method to my view layer in a vue component?如何将数据从 vue-resource 方法传递到 vue 组件中的视图层?
【发布时间】:2017-03-07 23:31:23
【问题描述】:

我有一个 resource.js,它是一个导出的 ES6 类:

import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export class Resource {

  getMovies () {
      // GET /someUrl
    return Vue.http.get('http://localhost:3335/cardname').then((response) => {
      console.log('success')
      return response
    }, (response) => {
      console.log('problem')
      return response
    })
  }

}

然后我将它导入到我的组件中并在视图/组件中传递数据:

<script>
  import { movies } from '../mock'
  import { Resource } from '../services/resource'
  const resourceService = new Resource()
  export default {
    name: 'hello',
    data () {
      return {
        msg: 'MovieRama',
        count: 0,
        movies: movies.movies,
        totalMovies: movies.total,
        test: null
      }
    },
    mounted: function () {
// Note this part
      let that = this
      resourceService.getMovies().then(function (result) {
        that.test = result
      })
    },
    methods: {
      boom: function () {
        console.log('Woho')
      },
      updateCount: function () {
        this.count++
      }
    }
  }
</script>

请注意mounted 方法。为什么我需要保持这样的范围才能在 data () { } 中传递数据?

我正在查看 vue.js 文档,这似乎没有必要:

http://vuejs.org/guide/instance.html#Instance-Lifecycle-Hooks

【问题讨论】:

  • 你说的是let that=this的使用还是resourceService的使用?
  • let that = this 的使用,确实

标签: vue.js vue-component vue-resource


【解决方案1】:

由于您使用了匿名函数,因此当您调用this 时,它有自己的作用域。如果你使用箭头函数,你可以摆脱它

resourceService.getMovies().then((result) => {
  this.test = result
})

我还建议查看创建资源的文档:https://github.com/vuejs/vue-resource/blob/master/docs/resource.md

这是一种创建自动具有getupdatedelete 等方法的类的方法。

【讨论】:

  • 谢谢杰夫。似乎我的 ESLINT 检查器不允许返回箭头函数(出于最佳实践原因,我认为)
  • 箭头函数中允许返回语句。如果您只需要返回一个值,那么您甚至不需要弯曲的括号。 IE。 Vue.http.get('/foo').then(response =&gt; response.body) 返回响应的主体,以便您可以在其上链接承诺
  • 实际上 linter 不允许在箭头函数周围没有 { } 的情况下设置值 :) 所以我们很好。
  • 啊,是的,如果您要使用表达式,则需要波浪线。没有它们,你所能做的就是返回一个简单的值。
猜你喜欢
  • 2020-06-16
  • 2017-02-27
  • 2017-02-24
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 2018-08-24
相关资源
最近更新 更多