vuejs2: How to pass vuex store to vue-router components - vuejs2

In case when vue-router is not used, store can be passed to child components when declaring new Vue()
But I am using both vue-router and vuex. In this case how can I make store available to components. For e.g. my store.js is typical:
import Vue from 'vue'
import Vuex from 'vuex'
import jwt_decode from 'jwt-decode'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex);
Vue.use(VueAxios, axios);
export const store = new Vuex.Store({
state: {
jwt: localStorage.getItem('t'),
endpoints: {
obtainJWT: 'http://0.0.0.0:8000/auth/obtain_token',
refreshJWT: 'http://0.0.0.0:8000/auth/refresh_token'
}
},
mutations: {
updateToken(state, newToken){
localStorage.setItem('t', newToken);
state.jwt = newToken;
},
removeToken(state){
localStorage.removeItem('t');
state.jwt = null;
}
},
actions:{
obtainToken(username, password){
//commented code
},
refreshToken(){
//commented code
},
inspectToken(){
//commented code
}
}
});
My main.js file is as below:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
import { store } from './store'
console.log(store)
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
And router/index.js file is as below:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Signup from '#/components/signup/Signup'
import store from '../store.js'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
name: 'Login',
component: function (resolve) {
require(['#/components/login/Login.vue'], resolve)
}
},
{
path: '/signup',
name: 'Signup',
component: Signup
}
]
})
Now how can I pass store to my Signup component. Even though I am passing store in new Vue() it is not available in Signup component

I think the problem is that you importing store and you use the ../store.js,but when you import js file you dont have to use the .js so it has to be import store from '../store'
Also you dont have to pass the vuex store in components using vue-router.
So follow below the installation of vuex store and vue-router!
Vuex Store:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
propertiesName: 'PropValue'
},
getters: {},
mutations: {},
actions: {}
});
Vue-Router:
import Vue from 'vue'
import Router from 'vue-router'
import Page from '#/components/Page.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/Page',
name: 'Page',
component: Page,
},
//other routes
],
mode: 'history',
scrollBehavior(to, from, savedPosition) {
if(savedPosition){ //when use press back button will go at the position he was on the page
return savedPosition
}
if(to.hash){ //if has a hash positition to go
return { selector: to.hash } //go to the page in scrolled Position
}
return { x:0, y: 0 } //go to the page in scroll = 0 Position
}
})
main.js:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { store } from '../store/store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
Note:Doing that,now you have access of router and store in all your components
To use the store in your components:
this.$store.state.propertiesName
To use the router in your components:
this.$router.push({name: 'Page'})

Related

How can I salve the following Vue.js problem

I’m using vue-router version "^4.0.13". when I want to run (npm run watch) the following errors occur
WARNING in ./resources/js/app.js 7:8-17 export 'default' (imported as
'VueRouter') was not found in 'vue-router'
My project files are
app.js
require("./bootstrap");
window.Vue = require("vue").default;
import Vue from "vue";
import VueRouter from "vue-router";
import { routes } from "./routes";
Vue.use(VueRouter);
Vue.component(
"employees-index",
require("./components/employees/Index.vue").default
);
const router = new VueRouter({
mode: "history",
routes: routes
});
const app = new Vue({
el: "#app",
router: router
});
routs.js
import EmployeesIndex from "./components/employees/Index";
import EmployeesCreate from "./components/employees/Create";
import EmployeesEdit from "./components/employees/Edit";
export const routes = [
{
path: "/employees",
name: "EmployeesIndex",
component: EmployeesIndex
},
{
path: "/employees/create",
name: "EmployeesCreate",
component: EmployeesCreate
},
{
path: "/employees/:id",
name: "EmployeesEdit",
component: EmployeesEdit
}
];

Swapping vue components based on store

I am trying to create a vue app which will have 4 different templates, such as template1/list, template2/list, template3/list etc. the template version will be stored with the store such as store.template: 1.
I was wondering if there was a way to swap out the vue components in app to display the correct template based on this value?
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const routes = [
{
path: '/',
redirect: '/cases'
},
{
path: '/cases',
name: 'cases',
component: () => import(`../views/List${store.state.tempalte}`),
},
];
const router = new VueRouter({
mode: 'history',
routes
})
export default router
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
template: 1,
},
mutations: {},
actions: {},
modules: {},
getters: {}
})
This was one of the ways I thought it might be possible but it gives me an error store is not defined within this line component: () => import(`../views/List${store.state.template}`)

Vue.js using POST error(Sysntax but not find out)

Thank you for reading this question.
I got a syntax error, but I can't find where.
I am using Vue.js & bootstrap, I am working on shopping cart functionality. In order for endpoints to work you need to pass a special authentication header:
Authorization: kazuhisa.noguchi.ghsd75#gmail.com
import Vue from 'vue'
import App from './App.vue'
import BootstrapVue from 'bootstrap-vue'
import VueRouter from 'vue-router'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import MainPage from './components/MainPage.vue'
import HelpPage from './components/HelpPage.vue'
import ProductPage from './components/ProductPage.vue'
import CategoryPage from './components/CategoryPage.vue'
Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(VueRouter)
const router = new VueRouter({
routes: [{
path: '/',
component: MainPage
},
{
path: '/help',
component: HelpPage
},
{
path: '/products/:productId',
component: ProductPage
},
{
path: '/categories/:categoryAlias',
component: CategoryPage
}
],
mode: 'history'
})
axios.defaults.headers.common['Authorization'] = 'azuhisa.noguchi.ghsd75#gmail.com';
axios.post("https://euas.person.ee/user/carts/").then(
response => {
new Vue({
render: h => h(App),
router: router,
data: {
cart: response.data,
saveCard() {
axios.put("https://euas.person.ee/user/carts/" +
this.cart.id, this.cart)
}
}
}).$mount('#app')
}
};
All my best,

vue-router not pushing while inside a store

This is my store
import Vue from 'vue'
import Vuex from 'vuex'
import router from '#/main';
import mainStore from './modules/main-store';
import loginStore from './modules/login-store';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mainStore,
loginStore
}
});
and my login-store.js
//other imports
import router from '#/main';
const actions = {
forceLogout(){
localStorage.removeItem('token')
localStorage.removeItem('user')
delete API.defaults.headers.common['Authorization']
router.push('/login')
},
//other actions
}
And my router.js:
import store from './stores'
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes: [
{
path: '/login',
name: 'login',
component: Login,
},
]
//other routes
})
//... some router.afterEach and router.beforeEach
export default router
There is a case where I need the store to force a logout and this is how I do it, I call the forceLogout action from a file named api.js
import store from './../stores';
//....
if(error_msg == 'Not_Logged'){
store.dispatch('forceLogout')
}
//....
I've tried changing an import:
import router from 'vue-router'
//...
router.push('/login')
Same thing with importing
import router from '#/main'
router.push('/login')
and I keep on getting TypeError: Cannot read property 'push' of undefined
I don't see where you're exporting your router.
router.js should include export default router so then when you import router from '#/main' it actually imports something.

how to configure Vuejs so that router is picked up

I am trying to integrate vue-router in my app. In my admin.js, I have:
import Vue from 'vue'
import Router from 'vue-router'
import AdminHome from '../admin/home.vue'
import AdminMetroArea from '../admin/metro-area.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/metro-areas/', name: 'metro-areas', component: AdminMetroArea },
{ path: '/', component: AdminHome }
]
})
document.addEventListener('DOMContentLoaded', () => {
const admin_home = new Vue(AdminHome).$mount('#vue-admin-home');
})
and I call like:
<td>my metro: <router-link :to="{ name: 'metro-areas' }">{{metro_area.metro_area}}</router-link></td>
but I get the following error:
How do I configure my Vue app to pick up my router?
the Router needs to be supplied to Vue during initialization, explicitly:
new Vue({
router: Router
})
Where Router is your import Router from '...path'.
In Main.js file do the following thing:
import router from './router'
where './router' would be the path of your router file.
then,
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
},
data() {
return {}
}
})
Than, supply it to the Vue in the same file (Main.js). HAPPY CODING :)