关于vue中的this指向问题,debounce传入一个箭头函数就会报错了
来源:2-1 搜索框组件
前端SoEasy
2019-07-08 13:58:28
<template>
<div class="mine-search-box-wrapper">
<i class="iconfont icon-search"></i>
<input
class="mine-search-box"
type="text"
title="搜索框"
:placeholder="placeholder"
ref="input"
v-model="query"
>
<i
class="iconfont icon-close"
v-show="query"
@click="reset"
></i>
</div>
</template>
<script>
import {debounce} from 'assets/js/util';
export default {
name: 'MeSearchBox',
props: {
placeholder: {
type: String,
default: '暑假大放送,好货五折起'
}
},
data() {
return {
query: ''// 数据双向绑定
};
},
watch: {
query: debounce(function () {// 这里换成箭头函数就报错$emit不是个函数
this.$emit('query', this.query);
})
},
methods: {
focus() {
this.$refs.input && this.$refs.input.focus();
},
clear() {
this.query = '';
},
reset() {
// console.log(this.query);
this.clear();
this.focus();
}
}
};
</script>
<style lang="scss" scoped>
@import "~assets/scss/mixins";
$search-box-height: 30px;
.mine-search-box-wrapper {
display: flex;
align-items: center;
width: 100%;
height: $search-box-height;
padding: 0 7px;
background-color: #fff;
border-radius: $search-box-height / 2;
}
.iconfont {
color: $icon-color;
font-size: $icon-font-size-sm;
font-weight: bold;
}
.mine-search-box {
flex: 1;
background: none;
border: none;
margin: 0 6px;
color: #666;
line-height: 1.5;
}
</style>
1回答
好帮手慕码
2019-07-08
同学你好!
是的,修改为箭头函数会报错,因为this指向不同了,this.$emit就查找不到了
this指的是:
之前的this指的是:
如果帮助到了你 欢迎采纳 祝学习愉快~
相似问题