I'm creating an application based on this code from github.
I need change vue resources to axios, how i can do that ?
I would like to know how to do this keeping the structure of this code.
I'm using vue 3.
Anyone who can help would be very grateful :)
the full code i'm modifying: here
http:
import Vue from 'vue'
import VueResource from 'vue-resource'
import services from './services'
Vue.use(VueResource)
const http = Vue.http
http.options.root = 'https://localhost.com/api'
Object.keys(services).map(service =>{
services[service] = Vue.resource('', {}, services[service])
})
export { http }
export default services
http services:
import { services as auth } from '#/modules/auth'
export default {
auth
}
Actions:
import services from '#/http'
import * as types from './mutation-types'
export const ActionDoLogin = (context, payload) =>{
return services.auth.login(payload)
}
export const ActionSetUser = ({ commit }, payload) => {
commit(types.SET_USER, payload)
}
export const ActionSeToken = ({ commit }, payload) => {
commit(types.SET_TOKEN, payload)
}
Services:
export default {
login: { method: 'post', url: 'login' }
}
Main:
import { createApp } from 'vue'
import App from './App'
import router from './router'
import store from './store'
import './assets/scss/app.scss'
createApp(App).use(store).use(router).mount('#app')
Login view:
<script>
import {mapActions} from 'vuex'
export default {
data: () =>({
form:{
email:'',
pass:''
}
}),
methods:{
...mapActions('auth', ['ActionDoLogin']),
submit(){
this.ActionDoLogin(this.form).then(res =>{
console.log(res.data)
})
}
}
}
</script>
Related
I have a UserStore which contains some information about the current user. This store also is responsible for loggin in and out.
In order to make the getters available I map the getters to my computed attribute within my Vue component.
Unfortunately I get an error saying that it cannot access useUserStore before initilization.
This is my component:
<template>
//...
</template>
<script>
import {mapState} from "pinia"
import {useUserStore} from "../../stores/UserStore.js";
import LoginForm from "../../components/forms/LoginForm.vue";
export default {
name: "Login",
components: {LoginForm},
computed: {
...mapState(useUserStore, ["user", "isAuthenticated"]) //commenting this out makes it work
}
}
</script>
This is my store:
import { defineStore } from 'pinia'
import {gameApi} from "../plugins/gameApi.js"
import {router} from "../router.js";
export const useUserStore = defineStore("UserStore", {
persist: true,
state: () => ({
authenticated: false,
_user: null
}),
getters: {
user: (state) => state._user,
isAuthenticated: (state) => state.authenticated
},
actions: {
async checkLoginState() {
// ...
},
async loginUser(fields) {
// ...
},
async logutUser() {
// ...
}
}
})
And my main.js
import {createApp} from 'vue'
import App from './App.vue'
import gameApi from './plugins/gameApi'
import {router} from './router.js'
import store from "./stores/index.js";
createApp(App)
.use(store)
.use(router)
.use(gameApi)
.mount('#app')
And finally my store configuration:
import {createPinia} from "pinia"
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import {useUserStore} from "./UserStore.js";
const piniaStore = createPinia()
piniaStore.use(piniaPluginPersistedstate)
export default {
install: (app, options) => {
app.use(piniaStore)
const userStore = useUserStore()
const gameStore = useGameStore()
}
}
I wasn't able to initialize the store using the "old" way comparable with Vuex. Instead I had to make use of the setup() function Pinia Docu:
<script>
import {useUserStore} from "../../stores/UserStore.js";
export default {
name: "RegisterForm",
setup() {
// initialize the store
const userStore = useUserStore()
return {userStore}
},
data() {
return {
// ...
}
},
methods: {
checkLoginState() {
this.userStore.checkLoginState()
}
}
}
</script>
I have just started using Vue3, and am trying to use vuex to manage state. when using Vue2 I would call the store each time the app loads like this:
// mains.js
import VueRouter from "vue-router";
import Vuex from "vuex";
import router from "./routes";
window.Vue = require('vue').default;
Vue.use(VueRouter);
Vue.use(VueMoment);
Vue.use(Vuex);
const store = new Vuex.Store(storeDefinition);
const app = new Vue({
el: '#app',
router,
store,
components: {
"index": Index
},
async created() {
this.$store.dispatch("loadStoredState");
this.$store.dispatch("loadUser");
},
});
This is my vuex store that defines state, mutations and actions for vuex:
// store.js
import { isLoggedIn, logOut } from "./shared/utils/auth";
export default {
state: {
isLoggedIn: false,
user: {}
},
mutations: {
setUser(state, payload) {
state.user = payload;
},
setLoggedIn(state, payload) {
state.isLoggedIn = payload;
}
},
actions: {
loadStoredState(context) {
context.commit("setLoggedIn", isLoggedIn());
},
async loadUser({ commit, dispatch }) {
if (isLoggedIn()) {
try {
const user = (await axios.get("/user")).data;
commit("setUser", user);
commit("setLoggedIn", true);
} catch (error) {
dispatch("logout");
}
}
},
logout({ commit }) {
commit("setUser", {});
commit("setLoggedIn", false);
logOut();
}
},
getters: {}
}
This file manages a cookie for local storage that stores a boolean value for isLoggedIn:
// auth.js
export function isLoggedIn() {
return localStorage.getItem("isLoggedIn") == 'true';
}
export function logIn() {
localStorage.setItem("isLoggedIn", true);
}
export function logOut() {
localStorage.setItem("isLoggedIn", false);
}
But in Vue3 I am creating the main.js file like this:
// mains.js
const { createApp } = require('vue')
import Index from './Index.vue'
import createRouter from './router'
import { createStore } from 'vuex'
import storeDefinition from "./store";
const store = createStore(storeDefinition)
createApp(Index)
.use(createRouter())
.use(store)
.mount('#app')
How can I add the two calls to manage the store to the createApp function?
You can add the created hook to the root component by using the extends option with the component definition:
// main.js
import { createApp } from 'vue'
import Index from './Index.vue'
import createRouter from './router'
import { createStore } from 'vuex'
import storeDefinition from './store'
const store = createStore(storeDefinition)
createApp({
extends: Index,
created() {
this.$store.dispatch('loadStoredState')
this.$store.dispatch('loadUser')
},
})
.use(createRouter())
.use(store)
.mount('#app')
demo
When adding vuex or vue-router as plugin in vue and using the options api you could access these plugins with the this keyword.
main.js
import { createApp } from 'vue';
import i18n from '#/i18n';
import router from './router';
import store from './store';
app.use(i18n);
app.use(store);
app.use(router);
RandomComponent.vue
<script>
export default {
mounted() {
this.$store.dispatch('roles/fetchPermissions');
},
}
</script>
The this keyword is no longer available with the composition api which leads to a lot of repetitive code. To use the store, vue-router or the i18n library I have to import and define the following:
RandomComponent.vue with composition api
<script setup>
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
const router = useRouter();
const store = useStore();
const { t } = useI18n();
const { handleSubmit, isSubmitting, errors } = useForm('/roles/create', role, CreateRoleValidationSchema, () => {
store.dispatch('notifications/addNotification', {
type: 'success',
title: t('create_success', { field: t('role', 1) }),
});
router.push({ name: 'roles' });
});
</script>
Is there a way to avoid these imports and definitions and have a way to easily use these plugins like I could do with the options api?
There is no built-in way of doing that in Composition API and script setup.
What you could do is:
Create a plugins.js file that exports common bindings you want to import. For example:
export * from 'vuex'
export * from 'vue-router'
export * from 'vue-i18n'
And then you have only 1 import to do:
<script setup>
import { useStore, useRouter, useI18n } from './plugins'
const router = useRouter();
const store = useStore();
const { t } = useI18n();
const { handleSubmit, isSubmitting, errors } = useForm('/roles/create', role, CreateRoleValidationSchema, () => {
store.dispatch('notifications/addNotification', {
type: 'success',
title: t('create_success', { field: t('role', 1) }),
});
router.push({ name: 'roles' });
});
</script>
You can go even further by initiating the plugins like:
import { useStore, useRouter, useI18n } from './plugins'
export function initiateCommonPlugins() {
const router = useRouter();
const store = useStore();
const { t } = useI18n();
return { router, store, t }
}
And your code then will look like this:
<script setup>
import { router, store, t } from './initiate-plugins'
const { handleSubmit, isSubmitting, errors } = useForm('/roles/create', role, CreateRoleValidationSchema, () => {
store.dispatch('notifications/addNotification', {
type: 'success',
title: t('create_success', { field: t('role', 1) }),
});
router.push({ name: 'roles' });
});
</script>
Use unplugin-auto-import plugin
This plugin can eliminate all imports you want and is highly customizable. Haven't tried it yet but I have seen people recommend it.
Stick to Options API
Using Vue 3 doesn't mean that you have to use Composition API for creating components. You can use Options API along with script setup for composables instead of Mixins.
So Options API for components, Composition API for reusing code or advanced use-cases.
I want to use PersistedState https://github.com/robinvdvleuten/vuex-persistedstate with vuex but i can't get to setup correctly.
I have this module inside the store directory
export const auth = {
namespaced: true,
state: {
},
getters: {
countLinks: state => {
return state.links.length
}
},
mutations: {
SET_LINKS: (state, links) => {
state.links = links;
},
//Synchronous
ADD_LINK: (state, link) => {
state.links.push(link)
},
REMOVE_LINK: (state, link) => {
state.links.splice(link, 1)
},
REMOVE_ALL: (state) => {
state.links = []
}
},
actions: {
//Asynchronous
removeLink: (context, link) => {
context.commit("REMOVE_LINK", link)
},
removeAll ({commit}) {
return new Promise((resolve) => {
setTimeout(() => {
commit('REMOVE_ALL')
resolve()
}, 1500)
})
}
}
}
I have named this àuth.js
This is my index.js file also inside store directory
import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate"
import { auth } from './auth'
const dataState = createPersistedState({
paths: ['data']
})
const store = createStore({
modules: {
auth
},
plugins: [dataState]
})
I have a total of 7 modules i would like to load and use in various places in my application. To kick things off i just want to load auth module and use it in my home.vue page
This is the script section of my home.vue
import Footer from '#/components/Footer.vue'
import Header from '#/components/Header.vue'
import { mapGetters} from 'vuex'
import store from '../store';
export default {
name: 'Home',
components: {
Footer,Header
},
mounted () {
var links = ['http://google.com','http://coursetro.com','http://youtube.com'];
store.commit('SET_LINKS', links);
},
computed: {
...mapGetters([
'countLinks'
]),
}
}
This is my main.js file
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
import FlagIcon from 'vue-flag-icon'
import {store} from './store';
createApp(App).use(i18n).use(FlagIcon).use(store).use(router).mount('#app')
When i npm run serve, i get the error
10:7 error 'store' is assigned a value but never used
no-unused-vars
How should i correct this to be able to use auth.js module anywhere in my application?
I am using vue3 add apollo-composable & apollo/client for graphql client.
This is my main.ts configure file.
import {createApp, provide, h} from 'vue'
import App from './App.vue'
import {ApolloClient, InMemoryCache} from "#apollo/client";
import {DefaultApolloClient} from '#vue/apollo-composable'
import router from './router'
import './assets/sass/main.sass'
const defaultclient = new ApolloClient({
uri: process.env.VUE_APP_API_HOST,
cache: new InMemoryCache(),
headers: {
"TOKEN": "....."
}
})
createApp({
setup() {
provide(DefaultApolloClient, defaultclient)
},
render() {
return h(App)
}
}).use(router).mount('#app')
I don't know how to change the token in the view/Home.vue
I can get graphqldata but I want to change header option before useResult ....
export default defineComponent({
components: {
UserListTable,
},
setup() {
const { result } = useQuery(usersQuery)
const users = useResult(result, null, (data: { userAccounts: any; }) => data.userAccounts)