Document

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Router not working on 4.0.14 -> Use the vue-devtools stable to solve this #1338

Router not working on 4.0.14 -> Use the vue-devtools stable to solve this #1338

Comments

Version

Steps to reproduce

Add a normal router-link with a to-value and try to click it.

What is expected?

What is actually happening?

I don’t know how to use a specific version in jsfiddle so I cant reproduce it there =/

If I switch from 4.0.13 to 4.0.14 they stop working. The link renders fine but nothing happens when clicking it.

We’re using SSR and «vue»: «^3.2.31» and «vite»: «^2.8.6»

The text was updated successfully, but these errors were encountered:

@ansbar check console. If you get api.now() error, you can switch to 4.0.13

That’s from the Vue devtools plugin. And only happens if you are still on the 6.0 beta of Vue devtools.

Happened to me today when checking in another browser that still was on the 6.0 beta version instead of the stable one we released recently.

Solution: remove the beta, upgrade to the stable release

@LinusBorg should be, I can’t confirm because can’t always reproduce the bug.
Now switched to stable. If no bug all day, I’ll comment here.

Maybe it’s worth gracefully handle it somewhere. It could also serve as a hint to make users upgrade their devtools version 🙂

image

I can confirm uninstalling devtools beta (6.0.0.23?) and running 6.1.0 instead solved this issue.
Thank you @LinusBorg

same here, switch from beta to stable version of the vue dev tools help!

Just for fellow googlers (took me almost an hour to find this issue):

Читайте также:  Как провести диагностику роутера asus

Console error related to this is

Uncaught (in promise) TypeError: api.now is not a function at vue-router.esm-bundler.js:2489:31 at vue-router.esm-bundler.js:3296:37 at Array.forEach () at triggerError (vue-router.esm-bundler.js:3296:18) at vue-router.esm-bunder.js:3037:17 

I am having the same problem with same vue-router version 4.0.14 but without any errors on dev tools console. There is nothing logged, but the router links simply are not working. No feedback. Will try to uninstall and install again the dev tools. Try to confirm if that helps.

i can confirm the error is gone after updating to stable devtools.

This is a bug with «vue devtools 6.0.0 bate», Install the new version to solve

I am having the same problem with same vue-router version 4.0.14 but without any errors on dev tools console. There is nothing logged, but the router links simply are not working. No feedback. Will try to uninstall and install again the dev tools. Try to confirm if that helps.

@awacode21 I have the same problem(the beta devtool, and firstly need to open DevTools Vue panel ). It’s caused by the code behind:

function navigate (
e : MouseEvent = < >as MouseEvent
) : Promise < void | NavigationFailure >
if ( guardEvent ( e ) )
return router [ unref ( props . replace ) ? ‘replace’ : ‘push’ ] (
unref ( props . to )
// avoid uncaught errors are they are logged anyway
) . catch ( noop )
>
return Promise . resolve ( )
>

Update the node_modules/vue-router/dist/vue-router.esm-bundler.js const noop = () => < >; to const noop = (err) => < console.error(err)>; , the error that took me hours debugger finally was showed in console!!

image

think about to add some development log about noop ? It is diffcult to find the error when no error showed in console with router not change. @posva

Thanks guys, too much appreciate for all your comment. it’s a fantastic community.
I have tried and it works.

Step 1:
Change router/index.js from:

const router = createRouter( history: createWebHashHistory(), routes >) export default router
export const router = createRouter( history: createWebHashHistory(), routes >)

Step 2:
Change main.js from

import router from './router'
import  router > from './router'

Step 3:
Run command yarn serve will see the issue fixed.

Step4:
Change all code back. the issue will not back.

JasonGoemaat added a commit to JasonGoemaat/electron-devtools-installer that referenced this issue May 16, 2022

* [Old link](https://chrome.google.com/webstore/detail/vuejs-devtools/ljjemllljcmogpfapbkkighbhhppjdbg): ljjemllljcmogpfapbkkighbhhppjdbg * [New Link](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd): nhdogjmejiglipccpnnnanhbledajbpd I noticed when using the tools in my test app that routing stopped working once I opened the tools. Doing some research I found [this issue](vuejs/router#1338) about the router that said it only happens when using the 6.0 beta version of the devtools. Looking at the extension directory installed with this it does reference the beta: ```js "version": "6.0.0.21", "version_name": "6.0.0 beta 21", ``` Using the new id (nndogjme. ) in my code instead of VUEJS3_DEVTOOLS fixed the issue for me. Also the new one seems to be more current (March 30 2022 vs. December 20, 2021), is newer (6.1.4 vs. 6.0.0.21), has more stars (1808 vs. 127) and more users (1,000,000+ vs. 200,000+).

The same problem using «vue-router»: «^4.0.13»

solved, no problem with vue-router.

This will warn as it does in pina in 4.1 to help people notice the issue 🙂

You can’t perform that action at this time.

Источник

# Сбои при навигации

При использовании router-link Vue Router вызывает router.push для запуска навигации. В большинстве случаев ожидаемое поведение ссылок заключается в переходе на новую страницу, но есть несколько ситуаций при которых пользователь остаётся на той же странице:

  • Пользователь уже находится на странице, на которую пытается перейти
  • Навигационный хук прерывает навигацию вызовом next(false)
  • Навигационный хук выбрасывает ошибку или вызывает next(new Error())

При использовании компонента router-link ни один из этих случаев не будет логироваться как ошибка. Однако при использовании router.push или router.replace можно столкнуться с сообщением «Uncaught (in promise) Error» после которого в консоли последует более конкретное сообщение. Давайте разберемся как отличать сбои навигации.

В версии 3.2.0, навигационные сбои доступны через два необязательных коллбэка router.push : onComplete и onAbort . Начиная с версии 3.1.0, router.push и router.replace возвращают Promise если не указаны коллбэки onComplete / onAbort . Этот Promise разрешается вместо вызова onComplete и отклоняется вместо вызова onAbort .

# Обнаружение сбоев навигации

Сбой навигации будет экземпляром Error с парой дополнительных свойств. Проверить произошла ли ошибка в маршрутизаторе можно с помощью функции isNavigationFailure :

import VueRouter from 'vue-router' const  isNavigationFailure, NavigationFailureType > = VueRouter // попытка перехода к странице администрирования router .push('/admin') .catch(failure =>  if (isNavigationFailure(failure, NavigationFailureType.redirected))  // отображение уведомления пользователю showToast('Необходимо авторизоваться для доступа к панели администрирования') > >) 

Если опустить второй параметр в isNavigationFailure(failure) , то будет проверяться только, является ли ошибка сбоем навигации.

# Тип NavigationFailureType

Тип NavigationFailureType поможет разработчикам определять тип навигационного сбоя. Существует 4 различных типа:

  • redirected : внутри навигационного хука был вызван next(newLocation) для перенаправления в другое место.
  • aborted : внутри навигационного хука был вызван next(false) для отмены навигации.
  • cancelled : произошла полностью новая навигация до того, как текущая могла закончиться. Например, во время ожидания внутри навигационного хука был вызван router.push .
  • duplicated : навигация была предотвращена, потому что уже находимся в месте назначения.

# Свойства ошибок навигации

Все сбои навигации предоставляют доступ к свойствам to и from , отображающие для навигации в которой произошёл сбой местоположение места назначения и текущее местоположение соответственно:

// попытка получения доступа к странице администрирования router .push('/admin') .catch(failure =>  if (isNavigationFailure(failure, NavigationFailureType.redirected))  console.log(failure.to.path) // '/admin' console.log(failure.from.path) // '/' > >) 

Во всех случаях значения to и from будут объектами нормализованных маршрутов.

Источник

Vue 3 router doesn’t work. I don’t understand why

Expected result: after having configured 2 routes, accessing route 1 gives me a webpage. Accessing route 2 gives me another page.

Current result: whichever route/path i try to access, i am always presented with the default/initial page (The «App» page use at the initialization const app = createApp(App) ). My second page is never displayed. No error is displayed.

Project structure:

/src |- main.js |- components/ |- router/ |- router.js |- views/ |- App.vue |- App2.vue 
import < createApp >from 'vue' import App from './views/App.vue' import router from "./router/router" const app = createApp(App) app.use(router) app.mount('#app') 
import < createWebHistory, createRouter>from 'vue-router' import App from '../views/App.vue' import App2 from '../views/App2.vue' const routes = [ < path: '/', component: App >, < path: '/toto', component: App2 >] const router = createRouter(< history: createWebHistory(), routes >) export default router 

App.vue and App2.vue are vue files with noticably different content.

   

(I omitted the css code which i assume to be irrelevant to the issue)

  • When i access localhost:3000, i get the content of App.vue.
  • When i access localhost:3000/toto, i get the content of App.vue.
  • When i access locahost:3000/whatever (non-existent route), i get the content of App.vue.

I’m unable to find what i’m doing wrong.

If it helps: vite.config.js:

import < defineConfig >from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig(< plugins: [vue()] >) 

Источник

Vue.js vue-router не возвращает страницу с компонентом

Использую Vue.js и vue-router. Проблема заключается в том, что при нажатии на кнопку с параметром to=»login» url меняется на «http://localhost:8080/#/login» однако компонент не возвращается, а остается прежний и в консоль не выводится никаких ошибок. Т.е. внешний вид страницы не изменяется. В чем может быть проблема? В работе создано два компонента App.vue и login.vue. Переход осуществляется с html страницы, её код:

 import Vue from 'vue'; import VueRouter from 'vue-router'; import App from './App.vue'; import Login from './login.vue'; Vue.use(VueRouter); const router = new VueRouter(< routes: [ < path: "#", component: App >, < path: "/login", component: Login >] >); const app = new Vue( < router, render: function (createElement) < return createElement(App); >>).$mount('#app'); 
   

Источник

Почему не работает router-view?

5bf8f05a4ccb9323961527.jpeg

Всем привет!
Структура проекта:

          
import $ from 'jquery'; // import Vue from 'vue'; import Vue from 'vue/dist/vue.js'; import VueRouter from 'vue-router'; import Brands from './views/Brands.vue'; import Contacts from './views/Contacts.vue'; Vue.use(VueRouter); const router = new VueRouter( < routes: [ < path: '/brands', component: Brands >, < path: '/contacts', component: Contacts >] > ) new Vue(< el: '#app', router: router >)

package,json ( пакет router установлен ):

"devDependencies": < "css-loader": "^1.0.1", "extract-text-webpack-plugin": "^4.0.0-beta.0", "file-loader": "^2.0.0", "html-loader": "^0.5.5", "html-webpack-plugin": "^3.2.0", "node-sass": "^4.10.0", "path": "^0.12.7", "style-loader": "^0.23.1", "webpack": "^4.26.0", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" >, "dependencies":

5bf8f1cfbcd1c674753309.jpeg

В компонентах-роутах все так:

Суть вопроса:
На страничке эти компоненты появились

, а тот в index.html

, в котором я ожидаю рендеринг views/Brands.vue и views/Contacts.vue — не показывается.

В чем может быть проблема?
Спасибо.

Источник

Оцените статью
Adblock
detector