我有一个由发帖请求触发的返回数据(称为get_teams方法),但未传递到我的vue模板。我是VueJS的新手,有人可以告诉我我做错了什么吗?我是否无法将数据正确绑定到我的vue模板?
app.js
var app = new Vue({
el: '#app',
components: {
teamsTableTemplate
},
data: {
teams: null,
editable: true,
show_teams: false
},
methods: {
get_teams : function(){
this.reset_show('get_teams')
$.post(js_local.ajaxurl,{
action:'get_advisor_teams'
}).done(function(data){
this.teams = data
this.show_teams = true
console.log(this.teams)
}).fail(function(data){
console.log('fail @ { action : get_advisory_teams }')
})
}
}
})
teams-table-template.js
const teamsTableTemplate = {
template:
`
<table class="table tablesorter">
<thead class="text-primary">
<tr></tr>
</thead>
<tbody class="">
<tr v-for="team in teams">
<td>
<div class="form-check">
<label for="69cd1dbb353338" class="form-check-label">
<input id="69cd1dbb353338" type="checkbox" class="form-check-input"><span class="form-check-sign"></span>
<!---->
</label>
</div>
</td>
<td>
<p class="title">{{team.team_name}}</p>
<p class="text-muted">{{team.problem_statement_text}}</p>
</td>
<td class="td-actions text-right">
<button type="button" class="btn btn-link">
<!----><i class="tim-icons icon-pencil"></i></button>
</td>
</tr>
</tbody>
</table>
`,
props: ['teams','edit'],
data() {
return {
}
}
}
HTML
<div id="app">
<button @click="get_teams"></button>
<teams-table-template :teams="teams" :edit="editable" v-if="show_teams" />
</div>
答案 0 :(得分:2)
我认为this
不是.done()回调中的组件实例,因为您使用的是简单函数。也许使用箭头功能。
尝试更改:
get_teams() {
this.reset_show('get_teams')
$.post(js_local.ajaxurl,{
action:'get_advisor_teams'
}).done((data) => { // use arrow function
this.teams = data
this.show_teams = true
console.log(this.teams)
}).fail(function(data){
console.log('fail @ { action : get_advisory_teams }')
})
}
// also make sure get_teams() method is invoking from somewhere else
created() {
this.get_teams();
}
答案 1 :(得分:1)
像您一样使用回调会导致一些错误,所以我建议使用箭头函数()=>{...}
代替function(){...}
作为回调,因为您失去了this
的上下文:
get_teams : function(){
this.reset_show('get_teams')
$.post(js_local.ajaxurl,{
action:'get_advisor_teams'
}).done((data) => {
this.teams = data
this.show_teams = true
console.log(this.teams)
}).fail(function(data){
console.log('fail @ { action : get_advisory_teams }')
})
}
或通过将this
分配给名为that
的全局变量并在回调上下文中使用它:
get_teams : function(){
this.reset_show('get_teams')
let that=this;
$.post(js_local.ajaxurl,{
action:'get_advisor_teams'
}).done(function(data){
that.teams = data
that.show_teams = true
console.log(that.teams)
}).fail(function(data){
console.log('fail @ { action : get_advisory_teams }')
})
}