vue.js - 如何使用函数在 data() 上的变量内设置值?
问题描述
我正在 Laravel 应用程序中创建一个 Vue.js 组件。
在我通过 axios 请求捕获响应后,我无法将值放入方法 data() 的变量中
这是代码:
应用程序.js
require('./bootstrap')
window.Vue = require('vue')
Vue.component('card', require('./components/card.vue'))
let app = new Vue({
el: '#app'
})
卡片.vue
<script>
module.exports = {
props: [
'name'
],
data: function() {
return {
projects: [],
}
},
mounted() {
this.getProjects() // NOT WORK?
},
methods: {
getProjects: function() {
axios.get('/api/v1/getProjects').then(function (response) {
console.log(response.data)
this.projects = response.data // NOT WORK
}).catch(function (error) {
console.log(error)
}).then(function () {
})
},
}
}
</script>
解决方案
尝试添加.bind(this)
或替换function
为=>
:
getProjects: function() {
axios.get('/api/v1/getProjects').then((response) => {
console.log(response.data)
this.projects = response.data // NOT WORK
}).catch((error) => {
console.log(error)
}).then(function () {
})
},
推荐阅读
- android - 打开针对关键字搜索的第一个链接
- java - 如何将字符串解码为相应的地图?
- angular - 如何将基于 Angular 6 的 daterangepicker 合并到基于 Angular 7 的项目中?
- kylin - 如何知道 Cube 构建已经完成
- javascript - 如何从另一个对象 JavaScript 创建对象
- javascript - NodeJS:等待所有带有 Promises 的 foreach 完成,但从未真正完成
- javascript - Ctrl-Z/Y 使浏览器专注于最近更改的输入
- javascript - Google Cloud Functions - 通过 SSL 连接到 Cloud SQL
- microsoft-graph-api - 如何跨多个用户同步日历事件
- sql - 我的子查询返回多个值,我得到错误