[Vuejs]-How can I pass a paramater that is not contained in the url when routing to a component using Vue.js

0๐Ÿ‘

โœ…

no route declares no :url so this returns a blank page

Vuex 3

pass data with vuex

import { router } from 'src/routes'

const store = new Vuex.Store({
  modules: {
    router: {
      namespaced: true,

      state: () => ({
        url: null
      }),

      mutations: {
        setUrl(state, url) {
          state.url = url
        }
      },

      actions: {
        pushToMenuItem({ commit }, name, url) {
          router.push({ name: "menu-item", params: { link: name })
          commit('setUrl', url)
        }
      },
    }
  }
})

Sidebar.vue

...
  methods: {
    push_to(name, url){
        store.commit('router/pushToMenuItem', name, url)
    }
  }
...

Pinia / Vue 3

stores/router.js

export const useRouterStore = defineStore('router', () => {
  const url = ref()
  const router = useRouter()

  function pushToMenuItem(name, url) {
    router.push({ name: "menu-item", params: { link: name })
    url.value = url
  }

  return { url, pushToMenuItem }
})

Sidebar.vue

...
const { pushToMenuItem } = useRouterStore()
...
  methods: {
    push_to: pushToMenuItem 
  }
...

View.vue

<template>
    <div>
        <h1>{{route.params.link}}</h1>
        <h1>{{routerStore.url}}</h1>
    </div>
</template>


<script setup>
import { useRouterStore } from 'stores/router'
import { useRoute } from 'vue-router'

const routerStore = useRouterStore()
const route = useRoute()
</script>

Leave a comment