vue之箭头函数

发布时间 2023-04-06 20:07:02作者: 树苗叶子

说明

当在一个方法(函数)里面再定义一个方法(函数)时,内部的方法的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>

如图,此时点击按钮没有匹配上任何内容
image

解决方法一 重新定义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
                    }
                })
            }
        }
    })

如下图所示,筛选功能已生效
image

解决方法二 使用箭头函数

前头函数用于匿名函数,可以继承上一个函数的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)