Unwanted Reload Full Page #2233
-
i am learning vue router. in my example.js file i push a route when call my function. in the component change anything page will full reload when i use this example.js file. you can see here https://stackblitz.com/edit/vitejs-vite-iu7psv?file=src%2Fcomponents%2FLogin.vue change anything in login.vue file its reload full page. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Importing a function from an external module can bring in additional context or dependencies, especially if the module itself has reactive data or dependencies. This context might be causing the reactivity system to re-render. Defining the function within the <script setup> block keeps everything within the local scope of the component, avoiding any unintended reactivity or side effects from module imports. <template>
<div>
Login
<button @click.prevent="test">Click Me</button>
</div>
</template>
<script setup>
import router from '../router';
function test() {
router.push('/');
}
</script> |
Beta Was this translation helpful? Give feedback.
-
By importing the
The proper way is to use export default function test(router) {
router.push('/');
} And pass it in the component: <template>
<div>
Login e
<button @click.prevent="test($router)">Click Me</button>
</div>
</template>
<script setup>
import test from '../example.js';
const router = useRouter() // we could also pass `router`
</script> You can find more info about |
Beta Was this translation helpful? Give feedback.
By importing the
router
from the file where routes are declared you are not letting vue handle hmr properly:The proper way is to use
useRouter()
in Login. If you still want to the external function pass router as an argument:And pass it in the component: