[英]How to pass a variable to a function (inside Vue2 computed)?
I try uses vue2.js 我尝试使用vue2.js
Code: http://jsbin.com/futuqoniso/1/edit?html,js 代码: http : //jsbin.com/futuqoniso/1/edit?html,js
Console: http://output.jsbin.com/futuqoniso/1 控制台: http : //output.jsbin.com/futuqoniso/1
But a variable "sort" is always undefined. 但是变量“ sort”始终是不确定的。 How correctly to pass it in function?
如何正确传递它的功能?
computed: {
sortedArray: function() {
function compare(a, b, sort) {
console.log(sort);
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
return this.arrays.sort(compare);
}
}
I tried "this.sort" and other variants... 我尝试了“ this.sort”和其他变体...
You can access any of your data properties by specifying the keyword this
for example: 您可以通过指定关键字
this
来访问任何数据属性,例如:
console.log(this.sort)
and this should be : 这应该是:
<a href="#" @click="sort = 'name'">name</a>
<a href="#" @click="sort = 'sex'">sex</a>
not : 不:
<a href="#" @click="sort = name">name</a>
<a href="#" @click="sort = sex">sex</a>
Something like this: 像这样:
var string = new Vue({
el: '#string',
data: {
sort: 'name',
arrays: [{
name: 'sonya',
sex: 'woman'
}, {
name: 'sindell',
sex: 'woman'
}, {
name: 'kano',
sex: 'man'
}, {
name: 'subzero',
sex: 'man'
}]
},
computed: {
sortedArray: function() {
var sort = this.sort; // define variable from this
function compare(a, b) {
console.log(sort);
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
return this.arrays.sort(compare);
}
}
})
Also update template: 同时更新模板:
<p>{{sort}}
Sort by:
<a href="#" @click="sort = 'name'">name</a>
<a href="#" @click="sort = 'sex'">sex</a>
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.