无法获取Vue状态的元素(Vue.js / JS / TS)

时间:2019-11-27 20:38:25

标签: javascript typescript vue.js npm webpack

我今天遇到了Vue的一个问题。

在函数中,我无法从状态获取元素。 但是,当我使用console.log()状态时,该元素在那里。 如何解决?

代码:

export const actions: ActionTree<IState, IState> = {
    getUsers(context) {
      // eslint-disable-next-line no-console
      console.log('getUsers().context=', context);
      // eslint-disable-next-line no-console
      console.log('getUsers().context.state=', context.state);
      // eslint-disable-next-line no-console
      console.log('getUsers().context.state.baseURL=', context.state.baseURL);
      // do something...
    }
}

控制台的日志:

第一个日志正常。我可以看到 baseURL 的值。 enter image description here

第二个日志也可以。可以看到 baseURL 的值。 enter image description here

第三个日志有问题。我无法获取 baseURL 的值!!! enter image description here

package.json文件:

{
  "name": "ui",
  "version": "2.0.0-rc",
  "private": true,
  "author": "Leo Wu <wudongyin@gmail.com>",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.19.0",
    "core-js": "^3.3.2",
    "qs": "^6.9.1",
    "uuid": "^3.3.3",
    "vue": "^2.6.10",
    "vue-class-component": "^7.0.2",
    "vue-property-decorator": "^8.3.0",
    "vue-router": "^3.1.3",
    "vuetify": "^2.1.0",
    "vuex": "^3.0.1",
    "vuex-class": "^0.3.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-eslint": "^4.0.0",
    "@vue/cli-plugin-typescript": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "@vue/eslint-config-airbnb": "^4.0.0",
    "@vue/eslint-config-typescript": "^4.0.0",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "node-sass": "^4.12.0",
    "sass": "^1.19.0",
    "sass-loader": "^8.0.0",
    "typescript": "~3.5.3",
    "vue-cli-plugin-vuetify": "^2.0.2",
    "vue-template-compiler": "^2.6.10",
    "vuetify-loader": "^1.3.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "@vue/airbnb",
      "@vue/typescript"
    ],
    "rules": {
      "max-len": "off",
      "no-param-reassign": "off"
    },
    "parserOptions": {
      "parser": "@typescript-eslint/parser"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

如果您需要更多信息,请告诉我。
任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

感谢@acdcjunior和@TimWickstrom,
我终于找到了原因和解决方案。这是代码比较。主要区别在于在何处加载配置值。

原始代码(有问题)

new Vue({
  router,
  store,
  vuetify,
  render: h => h(App),
}).$mount('#app');

store.commit(UPDATE_BASE_URL, {
  baseURL: process.env.VUE_APP_BASE_URL,
});


工作代码:

  new Vue({
  router,
  store,
  vuetify,
  created() {
    this.$store.commit(UPDATE_BASE_URL, {
      baseURL: process.env.VUE_APP_BASE_URL,
    });
  },
  render: h => h(App),
}).$mount('#app');


S 工作代码的密码
enter image description here
希望它能帮助遇到类似问题的人。