export 'default' (imported as 'Vue') was not found in 'vue - vue.js

I'm trying to get the url of the backend, but I get an error while importing and it's not clear how to fix it.
warning in ./src/store/index.js
"export 'default' (imported as 'Vue') was not found in 'vue'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
backendUrl: "http://127.0.0.1:8000/api/v1"
},
mutations: {},
actions: {},
modules: {},
getters: {
getServerUrl: state => {
return state.backendUrl
}
}
})
export default store
working version:
import { createStore } from "vuex";
const store = createStore({
state: {
backendUrl: "http://127.0.0.1:8000/api/v1"
},
mutations: {},
actions: {},
modules: {},
getters: {
getServerUrl: state => {
return state.backendUrl
}
}
})
export default store

If you are using the vue-cli, I have found that the solution is to modify vue.config.js to include the devServer property. See the Vue CLI documentation
module.exports = {
devServer: {
disableHostCheck: true,
proxy: {
'/api-ezbook': {
target: 'http://localhost:80',
ws: false
}
},
public: 'http://localhost:8080'
}
// use to deploy
publicPath: '/'
// use to deploy to live server
// publicPath: '/location/on/server'
// in production:
// publicPath: '/'
}

Related

How to use Environment Variables inside Vue3+Vite component library?

I have created a component as part of my component library that I am building with Vue3 and Vite. Everything works well, except when I try to use environment variables. I want the app that consumes this component library to be able to provide the component with environment specific data.
I have played around and found that if I have a .env file as part of the component library project, I am able to access those variables, but I want to be able to provide that during runtime and not during build time.
Here is my vite.config.ts
import { defineConfig } from "vite";
import { resolve } from "path";
import vue from "#vitejs/plugin-vue";
import dts from "vite-plugin-dts";
export default ({ mode }) => {
return defineConfig({
optimizeDeps: {
exclude: ["vue-demi"],
},
plugins: [
vue(),
dts({
insertTypesEntry: true,
}),
],
server: {
open: true,
},
build: {
lib: {
entry: resolve(__dirname, "src/lib.ts"),
name: "complib",
fileName: "complib",
},
rollupOptions: {
external: ["vue"],
output: {
globals: {
vue: "Vue",
},
exports: "named",
},
},
},
});
};
The entry looks like:
import { App, install } from "vue-demi";
import TestComp from "./components/TestComp.vue";
import "./tailwind.css";
install();
export default {
install: (app: App) => {
app.component("TestComp", TestComp);
},
};
export { Header };
And here is a minimal component TestComp.vue:
<script setup lang="ts">
import { onMounted } from "vue";
onMounted(() => {
console.log(import.meta.env.VITE_TEST_VAR);
});
</script>
<template>
<span>Test Comp</span>
</template>

Vue x module Namespace

I'm stuck on a problem that I had already encountered and which was resolved with the namespaced but nothing helped.
This is my module:
const Algo1Module = {
namespaced: true,
state: {
questions: {
question1: "test",
question2: "",
question3: "",
question4: "",
question5: "",
question6: ""
}
},
getters: {
getMyQuestions(state) {
return state.questions;
}
}
};
export default Algo1Module; // export the module
This is my index.js from my store:
import Vuex from "vuex";
import createLogger from "vuex/dist/logger";
import algo1 from "#/store/modules/algo1.store";
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== "production";
export default new Vuex.Store({
modules: {
algo1
},
strict: debug,
plugins: debug ? [createLogger()] : []
});
And i try to access to my getters from my component like this :
<script>
import { mapGetters } from "vuex";
export default {
name: "Algo",
computed: {
...mapGetters("Algo1Module", ["getMyQuestions"])
}
};
</script>
But i have an error message in console : [vuex] module namespace not found in mapGetters(): Algo1Module/
I don't understand or I may have made a mistake.
Thank you for the answer you can give me.
It will take name that you set up when imported module, try algo1
Your module name is registered under algo1 name.
If you want to call it Algo1Module then register it in the store like that:
modules: {
Algo1Module: algo1,
}

Dependency not found - Vue Js

I have recently added axios to a file called services.js so it's better organised. This file is on my root folder.
#/services.js
import axios from "axios";
const axiosInstance = axios.create({
baseURL: " server url here",
});
export const api = {
get(endpoint) {
return axiosInstance.get(endpoint);
},
post(endpoint, body) {
return axiosInstance.post(endpoint, body);
},
};
Then I have a component called Post.vue in my view folder:
<template>
<section>
<div>
<ul></ul>
</div>
</section>
</template>
<script>
import { api } from "#/services.js";
export default {
name: "Post",
props: ["id"],
data() {
return {
post: null,
};
},
methods: {
getPost() {
api.get(`/post/${this.id}`).then(response => {
this.post = response.data;
console.log(this.post);
});
},
},
created() {
this.getPost();
},
};
</script>
<style></style>
I also have a router.ts file with all my routes:
import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import Home from "../views/Home.vue";
import Podcasts from "../views/Podcasts.vue";
import Post from "../views/Post.vue";
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: "/",
name: "home",
component: Home,
},
{
path: "/podcasts",
name: "podcasts",
component: Podcasts,
},
{
path: "/post/:id",
name: "post",
component: Post,
props: true,
},
],
});
export default router;
It's giving me a dependency error like #/services.js did not exist.
Unsure what's wrong at this stage.
Thanks a lot in advance for helping out
In a standard Vue CLI project, the # symbol resolves to /src
If your file is in the root of your project try
import { api } from '#/../services'
But personally, I'd move it into src
You can check the Webpack configuration using
vue inspect
Look for the resolve.alias rules.
Check your webpack configuration, depends on the version of webpack you have, there should be an alias # like this:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
"#": path.resolve(__dirname) // check the path here
}
}
};
Or if you are using vue.config.js
configureWebpack: {
name: name,
resolve: {
alias: {
'#': path.resolve(__dirname)// check the path here
}
}
},
Make sure the path is correctly set up. You mentioned you have another project working fine, which makes it a good reference.

Can't dispatch action defined in store sub file

In /store/index.js I have:
import Vue from "vue";
import Vuex from "vuex";
import auth from "./modules/auth";
Then in /store/modules/auth.js I have:
export const actions = {
login({ commit, dispatch }, payload) {
...
}
}
But when trying to dispatch my login() action from any component by doing dispatch("auth/login", {}), I get this error:
[vuex] unknown action type: login
Why?
[EDIT] as per Shivam Singh's comment here's my export part:
export default new Vuex.Store({
state: {
token: null
},
getters: {},
mutations: {},
actions: {},
modules: {
auth: {
namespaced: true
}
}
});
After adding auth inside modules: {}, I'm getting this error:
Uncaught TypeError: Cannot read property 'getters' of undefined
/store/modules/auth.js
import Vue from "vue";
import Vuex from "vuex";
import auth from "./modules/auth";
export default new Vuex.Store({
state: {
token: null
},
getters: {},
mutations: {},
actions: {},
modules: {
auth: { // it's registry name, will be used while accessing module content.
namespaced: true,
...auth // actual module content.
}
}
});
While registering the module, you are not providing the actual module
content.
Ref vue doc: https://vuex.vuejs.org/guide/modules.html#namespacing

Why Vuex-persist doesn't store anything in localStorage?

So, in my project (Vue-cli + TypeScript) I need to store user data to locaStorage. For this purpose I decide to use vuex-persist (npm plugin) alongside with vuex. But in DevTool, in localStorage doesn't appear anything. What is wrong in my code. Thank you in advance.
In precedent project I already used this combination of tools, and they work fine. In this project I use the same configuration, and it doesn't work . And this is the most strange thing.
This is StructureModule.ts
import { ActionTree, MutationTree, GetterTree, Module } from "vuex";
const namespaced: boolean = true;
interface IDataStructure {
name: string;
type: string;
description: string;
}
interface IStructureState {
name: string;
description: string;
props: IDataStructure[];
}
export interface IState {
structures: IStructureState[];
}
export const state: IState = {
structures: [
{
name: "",
description: "",
props: [
{
name: "",
type: "",
description: "",
},
],
},
],
};
export const actions: ActionTree<IState, any> = {
addNewDataStructure({ commit }, payload: IStructureState): void {
commit("ADD_DATA_STRUCTURE", payload);
},
updateDataStructure({ commit }, payload: IStructureState): void {
commit("UPDATE_EXISTING_DATA_STRUCTURE", payload);
},
clearDataStructure({ commit }, { name }: IStructureState): void {
commit(" CLEAR_DATA_STRUCTURE", name);
},
};
export const mutations: MutationTree<IState> = {
ADD_DATA_STRUCTURE(state: IState, payload: IStructureState) {
if (state.structures[0].name === "") {
state.structures.splice(0, 1);
}
state.structures.push(payload);
},
CLEAR_DATA_STRUCTURE(state: IState, name: string) {
state.structures.filter((structure: IStructureState) => {
if (structure.name === name) {
state.structures.splice( state.structures.indexOf(structure), 1);
}
});
},
UPDATE_EXISTING_DATA_STRUCTURE(state: IState, payload: IStructureState) {
state.structures.map((structure: IStructureState) => {
if (structure.name === payload.name) {
state.structures[state.structures.indexOf(structure)] = payload;
}
});
},
};
export const getters: GetterTree<IState, any> = {
dataStructureByName(state: IState, structName: string): IStructureState[] {
const structure: IStructureState[] = state.structures.filter((struct: IStructureState) => {
if (struct.name === structName) {
return struct;
}
});
return structure;
},
dataStructures(): IStructureState[] {
return state.structures;
},
};
export const StructureModule: Module<IState, any> = {
namespaced,
state,
mutations,
actions,
getters,
};
This is index.ts
import Vue from "vue";
import Vuex, { ModuleTree } from "vuex";
import VuexPersistence from "vuex-persist";
import { StructureModule , IState} from "./modules/StructureModule";
Vue.use(Vuex);
const storeModules: ModuleTree<IState> = {
StructureModule,
};
const vuexPersistentSessionStorage = new VuexPersistence({
key: "test",
modules: ["StructureModule"],
});
export default new Vuex.Store<any>({
modules: storeModules,
plugins: [vuexPersistentSessionStorage.plugin],
});
This is main.ts
import store from "#/store/index.ts";
import * as $ from "jquery";
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
global.EventBus = new Vue();
(global as any).$ = $;
Vue.config.productionTip = false;
console.log(store);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
This is vue.config.js
module.exports = {
transpileDependencies: ["vuex-persist"],
};
This is store in vue-devtool
And this is dev-tool localStorage
I expect that in localstorage to appear an storage with key "test" with predefined values, but instead of this localStorage is empty.
As said in the guide
The only way to actually change state in a Vuex store is by committing
a mutation
https://vuex.vuejs.org/guide/mutations.html
I don't see any mutation in your code.
Otherwise, you should take a look at https://github.com/robinvdvleuten/vuex-persistedstate, it seems to be more popular, and I've been using it without any problem.
Usage is very simple : you just need to declare a plugin inside your store:
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()],
})
I found solution for this problem.
In my case i just remove namespaced from
export const StructureModule: Module<IState, any> = {
namespaced, <----- This
state,
mutations,
actions,
getters,
};
It seems namespaced should be used only if you have more than one module.