import Vue from 'vue' imports “different”

2020-03-19 03:31发布

问题:

This question is probably more about Webpack and ES6 import than about Vue.

I'm writing a Vuex mutation that adds a new mykey: [] to an object in state. This needs to use Vue.set(state.myobj, 'mykey', []), so that the new array gains reactiveness.

However, when I import Vue from 'vue' to my mutations.js and use Vue.set(...) it doesn't fix the problem (it just does nothing). The problem seems to be that Vue is not the same Vue that I use in my main js file when creating the Vue object in my main.js file.

I've verified that the problem is related to the way Vue is imported to mutations.js. If I write window.MY_VUE = Vue in main.js and then use window.MY_VUE.set(...) in mutations.js, the new array works as expected, i.e. when I push to the array, the changes are correctly reflected in DOM. Naturally, comparing window.MY_VUE === Vue in mutations.js returns false.

Am I doing something wrong? What would be the correct way to fix the problem?

NB: As a workaround, I now replace the object:

state.myobj = { ...state.myobj, mykey: [] }

I'm using Vue 2.4.2, Vuex 2.4.0 and Webpack 2.7.0. I'm not using Webpack code-splitting.

回答1:

I found the immediate cause. I first noticed that when loading the app, "You are running Vue in development mode." was printed twice in the console. They were both from vue.runtime.esm.js:7417, but served from different urls. (Webpack urls, since I was running npm run dev.) I noticed I had two node_modules directories (at ./ and ../../), and for some reason Vue was loaded once from both places. Probably I had installed the npm packages somehow in the wrong order. Removing both node_modules dirs and running npm install again solved the problem: now I can import Vue from 'vue' in mutations.js, and Vue.set(...) works as expected.

Anyway, I'm still not exactly aware of the actual npm problem or how to not do it again.