I try a redirect after a post request is made, and I tried different things but nothing worked till now.
self.$router.push('/record')
Vue.$router.push('/record')
this.$router.push({ name: 'Record' })
Here is the updated code. with axios form component, app.js and main.js
axios.delete('/record/' + this.id)
.then((response) => {
this.$router.push('/record')
});
})
.catch(error => {
//
});
In my app.js
import VueRouter from "vue-router";
import router from "./router";
Vue.use(VueRouter);
new Vue({
router,
render: h => h(App)
}).$mount("#app");
router.js
import Vue from "vue";
import VueRouter from "vue-router";
import Record from './components/AddPerson';
Vue.use(VueRouter);
const routes = [
{
path: "/record",
name: "Record",
component: Record,
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
Do you trying to redirect to the same route?
The Vue cache the components, because this is more fast.
If this is your problem, you must do something like this:
<template>
<v-app>
<router-view :key="$route.fullPath" />
</v-app>
</template>
<script>
export default {
name: 'App',
};
</script>
axios
.delete(`/record/${this.id}`)
.then(response => {
this.$router.push({
name: 'Record',
query: { x: new Date().toISOString() },
});
})
.catch(error => {
//
});
Related
So, i want to vue router.push on my store.js, but i keep getting error Cannot read property 'push' of undefined
i've tried to import vue-router in my store.js, but still in vain
here's my app.js :
import Vue from 'vue'
import VueRouter from 'vue-router'
//Import and install the VueRouter plugin with Vue.use()
Vue.use(VueRouter)
import App from './views/App'
import Home from './views/Home'
import Login from './views/Login.vue'
import Register from './views/Register.vue'
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
name: 'home',
component: Home,
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
and here's my store.js :
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
accessToken: null,
loggingIn: false,
loginError: null
},
mutations: {
loginStart: state => state.loggingIn = true,
loginStop: (state, errorMessage) => {
state.loggingIn = false;
state.loginError = errorMessage;
},
updateAccessToken: (state, accessToken) => {
state.accessToken = accessToken;
},
logout: (state) => {
state.accessToken = null;
}
},
actions: {
doLogin({ commit }, loginData) {
commit('loginStart');
console.log(loginData)
axios.post('http://localhost:8000/api/login', loginData)
.then(response => {
console.log(response)
let accessToken = response.data.jwt;
document.cookie = 'jwt_access_token=' + accessToken;
commit('updateAccessToken', accessToken);
///this caused the error
this.$router.push({ path: '/' })
})
.catch(error => {
// commit('loginStop', error.response.data.error);
console.log(error)
commit('updateAccessToken', null);
console.log(error.response);
})
}
}
})
as you can see, after i call doLogin() function, and using axios, it stop at the this.$router.push({ path: '/' }) line, causing error.
You need to make a router.js file
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
...
})
export default router
In app.js replace the import of the vue-router to your new router.js and remove Vue.use(Router).
In the store, this is not the Vue instance.
Import the router.js in your store.js;
import router from './router'
Then you can access it like this;
router.push({ path: '/' })
I also noticed that you haven't add the store to the Vue instance. Import and add in app.js.
import store from './store'
...
const app = new Vue({
el: '#app',
components: { App },
router,
store //<<<<<<<<
});
I realize a progressive application web app under view and I have a problem for the use of the mobile camera. I have a blank page. Here is my file seen for the camera:
<template>
<div class="container" id="app">
<router-link class="waves-effect waves-light btn" to="/livreur" #click.native="hideMenu"><i class="material-icons">arrow_back</i>
</router-link>
<div class="camera-modal">
<video ref="video" class="camera-stream"/>
</div>
</div>
</template>
<script>
var constraints = {
audio: false,
video: {
facingMode: {exact: 'environment'}
}
}
export default {
mounted () {
navigator.mediaDevices.getUserMedia(constraints)
.then(function (mediaStream) {
var video = document.querySelector('video')
video.srcObject = mediaStream
video.onloadedmetadata = function (e) {
video.play()
}
})
.catch(function (err) {
console.log(err.name + ': ' + err.message)
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
My file main.js:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import Axios from 'axios'
import VueSignature from 'vue-signature-pad'
Vue.prototype.$http = Axios
const token = localStorage.getItem('user-token')
if (token) {
Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}
Vue.use(VueSignature)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
My router.js file:
import Vue from 'vue'
import Router from 'vue-router'
import store from './store.js'
import Home from '#/components/Home'
import Delivered from '#/components/Delivered'
import Absent from '#/components/Absent'
import Refused from '#/components/Refused'
import Livreur from '#/components/preprations/Livreur'
import Prepa from '#/components/preprations/Prepa'
import Scan from '#/components/preprations/Scan'
import Login from '#/components/Login'
Vue.use(Router)
let router = new Router({
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/delivered',
name: 'delivered',
component: Delivered
},
{
path: '/absent',
name: 'absent',
component: Absent
},
{
path: '/refused',
name: 'refused',
component: Refused
},
{
path: '/livreur',
name: 'livreur',
component: Livreur
},
{
path: '/prepa',
name: 'prepa',
component: Prepa
},
{
path: '/scan',
name: 'Scan',
component: Scan
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
export default router
I tried to change the constraints but nothing helps, I try the default values but it does not work.
I do not see where it's blocking at all. Thank you for your help.
So I have a simple router file, that imports different routes for different parts of my website, so:
general.js (one of my route files)
import Home from '../../components/home/home'
const routes = [{
name: 'home',
path: '/',
component: Home
}]
export default routes
router.js
import Vue from 'vue'
import Router from 'vue-router'
import GeneralRoutes from './general'
Vue.use(Router)
const routes = Array.prototype.concat(
GeneralRoutes
)
const router = new Router({
mode: 'history',
routes
})
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
next({replace: true, name: 'login'})
}
next()
})
export default router
That is my router, now in my app.js, I simply use it like so:
import Vue from 'vue'
import Router from './core/routes/router'
new Vue({
el: '#app',
data: () => ({
user: ''
}),
Router,
});
But this is throwing an error saying the following:
[Vue warn]: Error in render: "TypeError: Cannot read property
'matched' of undefined"
When I console.log the router, I get the following:
router is lowercase
import Vue from 'vue'
import Router from './core/routes/router'
new Vue({
el: '#app',
data: () => ({
user: ''
}),
router: Router
});
How do we get access to the Vue router instance from within our actions.ts file? this.$router and this.$route aren't available in the following context:
boot.ts:
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from './services/store'
import * as log from 'loglevel'
Vue.use(VueRouter);
log.setLevel("trace");
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
new Vue({
el: '#app-root',
router: router,
store: store,
render: h => h(require('./layouts/app.vue.html'))
});
actions.ts:
import { http, httpClass } from './http';
import { DomainAppModel } from '../models/domainApps';
import Vue from 'vue';
var actions = {
LOGOUT: function ({ commit }, params) {
return new Promise((resolve, reject) => {
http.logout().then(result => {
commit('CLEAR_STATE');
// this.$router and this.$route not available
this.$router.push({
path:"login",
query: {
sessionTimedout: true,
redirect: this.$route.fullPath
}
});
});
});
}
}
export default actions
$router:
In order to access $router in the store actions you can do it like this:
move your router declaration to a separate file named router.ts
const router = new VueRouter({
routes,
linkActiveClass: "active"
});
export default router;
Import your router in actions.ts and use it instead of this.$router like this:
import router from './router';
// then use the router like this
router.push({path: 'login'})
$route.fullPath
Concerning $route.fullPath, you can pass it as a property of the payload when the action is dispatched
this.$store.dispatch('LOGOUT', {redirectPath: this.$route.fullPath})
then use it like this in the LOGOUT action
router.push({path:"login", query: {
sessionTimedout: true,
redirect: params.redirectPath
}});
I'm getting the following error when trying to implement vue-router.
Unknown custom element: <router-view> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
Where do I need to provide the name option?
A lot of the tutorials I'm looking at seem to be an older version of vue-router. I follow the set-up process but can't get it to work.
Might there be something special I have to do when using the webpack cli template?
I'm also using the vue-router cdn.
Here's my main.js
import Vue from 'vue'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
const routes = [
{ path: '/', component: App },
{ path: '/info', component: ResourceInfo }
]
const router = new VueRouter({
routes
})
/* eslint-disable no-new */
var vm = new Vue({
el: '#app',
components: { App },
created: function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Get info for currently signed in user.
console.log(user);
vm.currentUser = user;
console.log(vm.currentUser);
} else {
// No user is signed in.
}
})
// Import firebase data
var quizzesRef = db.ref('quizzes');
quizzesRef.on('value', function(snapshot) {
vm.quizzes = snapshot.val();
console.log(vm.quizzes);
})
var resourcesRef = db.ref('resources');
resourcesRef.on('value', function(snapshot) {
vm.resources.push(snapshot.val());
console.log(vm.resources);
})
var usersRef = db.ref('users');
usersRef.on('value', function(snapshot) {
vm.users = snapshot.val();
console.log(vm.users);
})
},
firebase: {
quizzes: {
source: db.ref('quizzes'),
asObject: true
},
users: {
source: db.ref('users'),
asObject: true
},
resources: db.ref('resources')
},
data: function() {
return {
users: {},
currentUser: {},
quizzes: {},
resources: []
}
},
router,
render: h => h(App)
})
And my App.vue
<template>
<div id="app">
<navbar></navbar>
<resource-info :current-user="currentUser"></resource-info>
<router-view></router-view>
</div>
</template>
<script>
import Navbar from './components/Navbar'
import ResourceInfo from './components/ResourceInfo'
export default {
name: 'app',
props: ['current-user'],
components: {
Navbar,
ResourceInfo
}
}
</script>
<style>
</style>
In your main.js file, you need to import VueRouter as follows:
import Vue from "vue" // you are doing this already
import VueRouter from "vue-router" // this needs to be done
And below that, you need to initialize the router module as follows:
// Initialize router module
Vue.use(VueRouter)
Other than the above, I cannot find anything else missing in your code, it seems fine to me.
Please refer to the installation page in docs, under NPM section:
http://router.vuejs.org/en/installation.html
First install vue router by using "npm install vue-route" and follow the bellow in main.js
import Vue from 'vue'
import Router from 'vue-router'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
Vue.use(Router)
var router = new Router({
hashbang: false,
history: true,
linkActiveClass: 'active',
mode: 'html5'
})
router.map({
'/': {
name: 'app',
component: App
},
'/info': {
name: 'resourceInfo',
component: ResourceInfo
}
})
// If no route is matched redirect home
router.redirect({
'*': '/'
});
// Start up our app
router.start(App, '#app')
This might be solve your problem
You forgot to import vue-router and initialize VueRouter in main.js
import VueRouter from "vue-router"
Vue.use(VueRouter)