在vue2的methods方法中无法获取到this对象

这几天突然想将学习下vue2,就写了个demo,用了vue2vuex2vuex2相比于vuex1有个不错的特性,就是能在创建store阶段就将actionsgetters给注册了,然后component中可以通过mapActionsmapGetters取得注册了的actionsgetters。但是在实际开发中却遇到了个问题,就是我无法在methods中取得this对象,在之前的vue1中是可以取得的,是我代码写错了吗?还是vue2本身就是这样的?

Hello.vue

<template>
  <div class="hello">
    <h1>{{ getText() }}</h1>
    <input type="text" class="text" :value="getText()" @keyup="setText($event)">
  </div>
</template>

<script>
  import {mapActions, mapGetters} from 'vuex'
  import {SET_TEXT} from '../vuex/mutation-types'

  export default {
    name: 'hello',
    data () {
      return {
        ...mapGetters(['getText'])
      }
    },
    methods: {
      ...mapActions([SET_TEXT]),
      setText: (e) => {
        let text = e.target.value.trim()
        console.log(this, text)
        this.SET_TEXT(text)
      }
    }
  }
</script>

store

import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import getters from './getters'
import mutations from './mutations'

Vue.use(Vuex)

const state = {
  text: 'Hello World'
}

export default new Vuex.Store({
  actions,
  getters,
  mutations,
  state
})

浏览器报错

图片描述

阅读 16.3k
1 个回答

原因:methods 里面箭头函数中的 this 不是指向 vue 实例

解决:methods 不使用 箭头函数

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题