問題:
在vuex組件中的mutations屬性中的定義的函數,有時會要用到vue這個對象。正常在其他的地方使用是通過this這個變量來獲取,但是在mutations定義的函數中this指定的是Vuex這個當前對象。
辦法:
在main.js中通過一個變量接收實例化的Vue對象,然以導出這個變量,這樣在其他地方可以通過導入這個變量來使用Vue對象。
// main.js const vue = new Vue({ el: '#app', router, store, components: {App}, template: '<App/>' }); export default vue;
在Vuex中使用
import vue from '../main' export default new Vuex.Store({ mutations: { Test(state) { console.log(vue); } } })