在vuex的mutations中使用vue的小技巧

問題:

  在vuex組件中的mutations屬性中的定義的函數,有時會要用到vue這個對象。正常在其餘的地方使用是經過this這個變量來獲取,可是在mutations定義的函數中this指定的是Vuex這個當前對象。vue

辦法:

  在main.js中經過一個變量接收實例化的Vue對象,然以導出這個變量,這樣在其餘地方能夠經過導入這個變量來使用Vue對象。vuex

// main.js
const vue = new Vue({
  el: '#app',
  router,
  store,
  components: {App},
  template: '<App/>'
});
export default vue;

  在Vuex中使用app

import vue from '../main'

export default new Vuex.Store({
    mutations: {
        Test(state) {
            console.log(vue);
        }
    } 
})
相關文章
相關標籤/搜索