关于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就查找不到了

http://img.mukewang.com/climg/5d22fe1d0001ec5004080118.jpg

this指的是:

http://img.mukewang.com/climg/5d22fd7d0001333505290495.jpg

之前的this指的是:

http://img.mukewang.com/climg/5d22fec200013d2704420185.jpg

如果帮助到了你 欢迎采纳 祝学习愉快~

0

0 学习 · 10739 问题

查看课程