vue之箭头函数
说明
当在一个方法(函数)里面再定义一个方法(函数)时,内部的方法的this指向会有问题,如下:
<body>
<div id="app">
<h1>{{l1}}</h1>
<button @click="clickFunc">点我</button>
</div>
</body>
<script>
vm = new Vue({
el:'#app',
data:{
myText: 'ab',
l1: ['a', 'ab', 'atd', 'b', 'd']
},
methods:{
clickFunc(){
this.l1 = this.l1.filter(function (item){
if(item.indexOf(this.myText) >= 0){
return true
}else{
return false
}
})
}
}
})
</script>
如图,此时点击按钮没有匹配上任何内容
解决方法一 重新定义this
第一种解决方法是,在内部函数外重新定义一下this,例如
<script>
vm = new Vue({
el:'#app',
data:{
myText: 'ab',
l1: ['a', 'ab', 'atd', 'b', 'd']
},
methods:{
clickFunc(){
let _this=this
this.l1 = this.l1.filter(function (item){
if(item.indexOf(_this.myText) >= 0){
return true
}else{
return false
}
})
}
}
})
如下图所示,筛选功能已生效
解决方法二 使用箭头函数
前头函数用于匿名函数,可以继承上一个函数的this
无参数的箭头函数
let f = function () {
console.log('123')
}
f()
// 修改为箭头函数写法
let f = () => { // 省略了function
console.log('123')
}
f()
有一个参数的箭头函数
let f = function (item) {
console.log(item)
}
f('hello world')
// 修改为箭头函数
let f = item => { // 可以省略扩号(括号也可以不省略)
console.log(item)
}
f('hello world')
有两个参数的箭头函数
let d1 = {'name': 'Hello World'}
let f = function (item, key) {
console.log(item, key)
}
f(d1)
// 使用前头函数
let f = (item, key) => { // 两个参数必须加括号
console.log(item, key)
}
f(d1)
有一个参数一个返回值的箭头函数
let f = function (item) {
return item + '!!!!'
}
res = f('hello world')
// 使用匿名函数
let f = item => item + '****' // 省略了return
res = f('hello world')
console.log(res)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类