1

In VueJS 2 with vue-router 2 I am using a parent view with subcomponents like this:

WidgetContainer.vue with route /widget_container/:

<template>
  <component :is="activeComponent"></component>
</template>

<script>
  import WidgetA from './components/WidgetA'
  import WidgetB from './components/WidgetB'

  export default {
    name: 'WidgetContainer',
    components: {
      WidgetA,
      WidgetB
    },
    data () {
      return {
        activeComponent: 'widget-a'
      }
    }
  }
</script>

In WidgetA I have the option of selecting a widget id

<template>
// v-for list logic here..
<router-link :to="{ path: '/widget_container/' + widget.id }"><span>{{widget.name}}   </span></router-link>
</template>

<script>
    export default {
    name: 'WidgetA',
    data() {
      return {
        widgets: [
          { id: 1,
            name: 'blue-widget'
          }]}}

routes.js:

export default new Router({
  routes: [
    {
      path: '/widget_container',
      component: WidgetContaner
    },
    {
      path: '/widget_container/:id?',
      redirect: to => {
        const { params } = to
        if (params.id) {
          return '/widget_contaner/:id'
        } else {
          return '/widget_container'
        }
      }
    }]})

From the WidgetContainer if the route is /widget_container/1 (where '1' is the id selected in WidgetA) I want to render WidgetB, but I cant work out:

1) how to pass the selected widget id into the router-link in WidgetA 2) How to know in WidgetContainer the the route is /widget_contaner/1 instead of /widget_container/ and render WidgetB accordingly.

Any ideas?

2
  • Can you show your router config as well. Commented Mar 13, 2017 at 8:21
  • @Saurabh, done see routes.js section. Im really unsure about the path: 'widget_container/:id?' setup Commented Mar 13, 2017 at 8:33

2 Answers 2

1

You can pass data to parent using by emitting event, you can see more details around here and here.

Once the data is change, you can watch over it and update the variable which has stored your widget.

Another option, if communication between components become unmanageable over time is to use some central state management, like vuex, more details can be found here.

Sign up to request clarification or add additional context in comments.

Comments

1

Wouldn't it be easier and more scallable to use Vuex for that? Just commit id to store and than navigate ?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.