【问题标题】:VueJS - Vue is not definedVueJS - 未定义 Vue
【发布时间】:2019-03-09 01:55:48
【问题描述】:

我挑战自己编写一个从 API 获取数据并将其显示在各种组件中的应用程序。我对 VueJS 很陌生。我使用 VueResource 访问 API,使用 VueX 进行状态管理。 我已经设置了我的商店,我已经添加了动作、突变和吸气剂等。一旦我在我的组件中添加 created 生命周期方法,我就会收到一个错误:

ReferenceError: Vue is not defined
    at Store.eval (eval at <anonymous> (build.js:1017), <anonymous>:11:3)
    at Array.wrappedActionHandler (eval at <anonymous> (build.js:1338), <anonymous>:711:23)
    at Store.dispatch (eval at <anonymous> (build.js:1338), <anonymous>:433:15)
    ...

我的代码如下所示:

main.js

import Vue from 'vue'
import App from './App.vue'
import VueResource from 'vue-resource'
import store from './store/store'

Vue.use(VueResource);

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    products: []
  },
  getters,
  actions,
  mutations
})

export default store

App.vue

<template>
   ...
</template>

<script>
    import { FETCH_MEALS } from './store/types';

    export default {
      //load meals on page load
      created() {
        this.$store.dispatch(FETCH_MEALS)
      },
      computed: {
        meals() {
          return this.$store.getters.meals
        },
        salads() {
          return this.$store.getters.salads
        },
        lunches() {
          return this.$store.getters.lunches
        },
        starters() {
          return this.$store.getters.starters
        }
      }
    }
</script>

我被卡住了,我不知道我做错了什么。你有什么想法吗?

更新

我使用 vue-cli 生成的典型样板,并使用 Webpack 构建 main.js。

actions.js

import { API_ROOT } from '../config'
import * as types from './types';

export default {
  [types.FETCH_MEALS]: ({commit}) => {
    Vue.http.get(API_ROOT + '/meals.json')
    .then(response => response.data)
    .then(meals => {
      commit(types.SET_MEALS, meals)
    })
  }
};

mutations.js

import * as types from './types';

export default {
    [types.MUTATE_UPDATE_VALUE]: (state, payload) => {
        state.value = payload;
    }
};

getters.js

import * as types from './types';

export default {
    [types.VALUE]: state => {
        return state.value;
    }
};

【问题讨论】:

  • 您能告诉我们您是如何构建您的main.js 的吗?您不能直接从浏览器执行main.js。需要使用babelvue-loader 进行转译
  • @Ohgodwhy 我更新了我的问题。我使用 Webpack 构建 main.js

标签: vue.js vuex vue-resource


【解决方案1】:

我的猜测是您在未列出的内部使用Vue(如Vue.set()actions.jsmutations.jsgetters.js,但忘记加了:

import Vue from 'vue'

在该文件的开头。

【讨论】:

  • 我在原始问题中添加了actions.jsmutations.jsgetters.js 的代码源。我不在这些文件中使用 Vue.set。还有其他想法吗?
  • 哦,哇!我刚刚发现了问题。我在做Vue.http() 但不导入 Vue。问题解决了。谢谢你。你帮我解决了。
【解决方案2】:

在普惠制中

<asset:javascript src="/vuebundle.js"/>

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    相关资源
    最近更新 更多