这几天突然想将学习下vue2
,就写了个demo,用了vue2
和vuex2
。vuex2
相比于vuex1
有个不错的特性,就是能在创建store
阶段就将actions
和getters
给注册了,然后component
中可以通过mapActions
和mapGetters
取得注册了的actions
和getters
。但是在实际开发中却遇到了个问题,就是我无法在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
})
浏览器报错
原因:methods 里面箭头函数中的 this 不是指向 vue 实例
解决:methods 不使用 箭头函数