vue-項目模塊化中this 指向問題


在VUE項目中,我們想把一些主要的代碼抽到一個模塊中

export default {
  /**
   * 獲取本地的群列表數據
   * @param {*} params
   */
  getGroupList () {
    // 這里的this指向的是當前的對象,我們一般想要的是VUE實例的this
  }
}

有兩種方法,

方法一, 在調用這個方法的時候把this傳進來,但是假如這個模塊有很多個方法,每調一次都要傳this過來麻煩


方法二: 在 main.js中把VUEX實現導出了,然后在當前模塊引用

main.js

let vue = new Vue({
  components: { App },
  router,
  store,
  i18n,
  template: '<App/>'
}).$mount('#app')
export default vue

當前摸塊引用

/**
 * 群聊相關的增,刪,改,查
 */
import _this from '../../main.js'
export default {
  /**
   * 獲取本地的群列表數據
   * @param {*} params
   */
  getGroupList () {
    const getList = _this.$db.models.User
    getList.getUser({
      userId: _this.$store.getters.userId
    }).then(res => {
      console.log(res)
    })
  }

}

解決問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM