Two way binding between controller in routerview a

2019-07-09 23:23发布

I have a single page application which consists of a:

A navigation component which contains a title and a menu A router-view I'd like each component being presented in the router view which correspond to a state in the router, to update the title of the navigation component. How to go about passing the parameters from the components in the router-view to the outer navigation component.

I'm using vue 2.0

2条回答
狗以群分
2楼-- · 2019-07-09 23:59

You can just have a contain-all Main component which stores the current route, and pass it to the navigation and the router view component as the their props, then the situations are:

  • when Main's stored route changes, the nav will rerender accordingly.
  • for the router view component, watch the prop change, this.$router.push('/some/where') when it changes.
  • when the user clicks an item on the nav, it emits an event, along with the data (the route the user wants to go to), the parent receives the event, changes its stored route, which, according to the last 2 bullets, changes how nav and router view looks.

The routes have to be part of the parent, since vue uses a parent-to-child-only one-way data flow. Children can't communicate with each other without help from their common parent unless we use some approach described in the last paragrath.

For details on how to implement parent-child data sharing, see doc.

Above is the simplest solution, which gets dirty quickly when your routes go nested. If so, you'll need a global event bus for non-parent-child data passing, or, vuex if you're looking at a large app and want your global states contained well.

查看更多
一夜七次
3楼-- · 2019-07-10 00:07

I would recommending Vuex for this:

https://github.com/vuejs/vuex

This way you can access your Vuex store in the main component and display its title:

computed: {
  title () {
    return this.$store.state.title
  }
}

Then you'd set up a mutation to update the title and call this wherever required in your components. Now as Vue is reactive the title within the nav component will update.

Below is an abbreviated example:

Vuex Store:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    title: ''
  },
  mutations: {
    updateTitle (state, title) {
      state.title = title
    }
  }
})

Your App Root:

import Vue from 'vue'
import store from './vuex/store'
new Vue({
  el: '#app',
  store,
})

Nav component:

export default {
  computed: {
    title () {
      return this.$store.state.title
    }
  },
  ...

Any other component which needs to update your title:

import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations([
      'updateTitle' // map this.updateTitle() to this.$store.commit('updateTitle')
    ]),
  },
  // if you wanted to call it on mount
  mounted () {
    this.updateTitle('hello')
  },
  ...
查看更多
登录 后发表回答