Quasar App 路由问题

Quasar App Routing Problems

我现在正在开发 Quasar 应用程序。到目前为止,我只有一个登录页面和类星体提供的默认布局。我有一个单独的服务器,我在端口 100 设置了 运行。我已经设置了代理以将来自 axios 和 socket.io 的所有调用重定向到我的服务器,该服务器托管我的 mySQL 数据库应用。我已经设置了我的路线,如果我在浏览器的搜索中手动输入路线,我可以去它但是一旦我在我的登录中使用 this.$router.push() 去主页它不会导航到它。例如,我在端口 8080 上托管此应用程序。默认情况下,它将转到登录页面:"localhost:8080"。当登录进行身份验证时,应该使用 this.$router.push('/main') 将用户重定向到我的类星体应用程序中的主页。但是,它不会这样做。当我按下登录时,url 就变成了 "localhost:8080/?"。但是,如果我在浏览器中手动输入:"localhost:8080/main",它会将我引导至主页。 这是我的路线代码:

export default [
{ 
    path: '/', 
    component: () => import('components/login'),
  },

  {
    path: '/main',
    component: () => import('layouts/default'),
    children: [
      { path: '', component: () => import('pages/index') },
      { path: 'chat', component: () => import('components/chat')}
    ]
  },

  { // Always leave this as last one
    path: '*',
    component: () => import('pages/404')
  }
]

这是我的登录组件代码:

<template>
    <div>
        <form id="login" label="Login">
            <q-input type="text" float-label="Username" v-model="username" /> <br>
            <q-input v-model="password" type="password" float-label="Password" />
            <q-btn input type="submit" @click="authenticate()">Submit</q-btn>
        </form>
    </div>
</template>

<style>
    input{
        margin: 10px;
    }
    #login{
        vertical-align: middle;
        text-align: center;
    }
</style>

<script>

module.exports = {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    authenticate () {
      this.$axios.post('/api/login', {
        Username: this.username,
        Password: this.password
      })
        .then(response => {
          this.$Socket.emit('LoginInfo', {
            firstname: response.data[0].ClientFirstName,
            lastname: response.data[0].ClientLastName,
            name: response.data[0].ClientFirstName + ' ' + response.data[0].ClientLastName,
            userid: response.data[0].ClientID
          })
          console.log(this.$router)
          this.$router.push({path: '/main'})
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }
}
</script>

我花了几个小时试图搜索可能是什么问题,但到目前为止我没有找到任何有用的东西。也许这可能是一个错误?我的同事查看了我的代码,他也没有发现任何问题。希望你们能帮助我。非常感谢。

根据要求,服务器代码:

const Express=require('express');
const path=require('path');
var cors = require('cors')
var app = Express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "ChatDB"
});

con.connect(function(err) {
  if (err)throw err;
  /*let query="INSERT INTO Client(ClientUserName, ClientPassword, ClientFirstName, ClientLastName) VALUES(\"jeffrey\", \"penner\", \"Jeffrey\", \"Penner\")";
  con.query(query, function(err, result){
    if(err) throw err;
  })*/
  console.log("Connected!");
});

io.set('origins', 'http://localhost:8080');

app.use(Express.json())
//app.use('/public', Express.static(path.join(__dirname, 'public')));
app.use(cors());

app.post('/login', cors(), function(req, res){
  let a=req.body.Username;
  let b=req.body.Password;
  let query="SELECT ClientID, ClientFirstName, ClientLastName FROM Client WHERE ClientUsername=\'" + a + "\' AND ClientPassword=\'" + b + "\';";
  con.query(query, function (err, rows) {
    if (err){
      throw err;
    }
    else if(rows.length)
    {
      console.log(rows);
      res.json(rows);
    }
  })
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
  socket.on('LoginInfo', function(data) {
    console.log(data)
  });
})

http.listen(100, function(){
  console.log('listening on *:100')
});

index.js 路由器代码:

import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from './routes'

Vue.use(VueRouter)

const Router = new VueRouter({
  /*
   * NOTE! Change Vue Router mode from quasar.conf.js -> build -> vueRouterMode
   *
   * If you decide to go with "history" mode, please also set "build.publicPath"
   * to something other than an empty string.
   * Example: '/' instead of ''
   */

  // Leave as is and change from quasar.conf.js instead!
  mode: process.env.VUE_ROUTER_MODE,
  base: process.env.VUE_ROUTER_BASE,
  scrollBehavior: () => ({ y: 0 }),
  routes
})

export default Router

I think you are not importing the routes in main.js as it should and thus the router object it is not accessible in all components.

我将向您展示我是如何完成路线的(简化示例)。

路线

import Vue from 'vue'
import Router from 'vue-router'
import Homepage from '@/pages/home/Home.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Homepage',
      component: Homepage
    },
  ],
  mode: 'history',
  base: '/'
})

main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router' //import the router

new Vue({
  el: '#app',
  router, //use it in vue instance
  template: '<App/>',
  components: { App }
})

并且您将有权访问要使用的所有组件:

this.$router.push({path: '/yourPath'})

请注意,您还可以为路线使用名称并按名称调用它们,例如:

  routes: [
    {
      path: '/myPath',
      name: 'myPath',
      component: cmp
    }
  ]

然后像这样在你的组件中调用路由:

this.$router.push({name: 'myPath'})

有关更多信息,请查看 named routes

问题其实很简单——你的this.$router.push({path: '/main'})行中的this指的是函数的局部作用域,而不是全局作用域。 因此,在顶层,在调用 axios POST 之前,您应该:

var _this = this

然后使用该上下文在您的 axios 代码中调用路由器。

_this.$router.push({path: '/main'})

只是 Javascript 件事。

你好,我有同样的问题,我通过更新 quasar.conf.js 中的值来修复它,在构建括号中我已经把

build: {
  vueRouterMode: 'history', // available values: 'hash', 'history'
  publicPath: '/',

我的路由文件指向这个


const routes = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/Index.vue') }
    ]
  },
  {
    path: '/catalog',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/Catalog.vue') }
    ]
  },
  // Always leave this as last one,
  // but you can also remove it
  {
    path: '*',
    component: () => import('pages/Error404.vue')
  }
]

现在一切正常