Passing props to Vue.js components instantiated by Vue-router

前端 未结 6 1072
日久生厌
日久生厌 2020-11-29 04:15

Suppose I have a Vue.js component like this:

var Bar = Vue.extend({
    props: [\'my-props\'],
    template: \'

This is bar!

\' });
<
6条回答
  •  失恋的感觉
    2020-11-29 05:05

    This question is old, so I'm not sure if Function mode existed at the time the question was asked, but it can be used to pass only the correct props. It is only called on route changes, but all the Vue reactivity rules apply with whatever you pass if it is reactive data already.

    // Router config:
    components:
    {
        default: Component0,
        named1: Component1
    },
    props:
    {
        default: (route) => {
            // 
            return { prop1: store.importantCollection }
        },
        named1: function(route) {
            // 
            return { anotherProp: store.otherData }
        },
    }
    

    Note that this only works if your prop function is scoped so it can see the data you want to pass. The route argument provides no references to the Vue instance, Vuex, or VueRouter. Also, the named1 example demonstrates that this is not bound to any instance either. This appears to be by design, so the state is only defined by the URL. Because of these issues, it could be better to use named views that receive the correct props in the markup and let the router toggle them.

    // Router config:
    components:
    {
        default: Component0,
        named1: Component1
    }
    
    
    
    
    

    With this approach, your markup declares the intent of which views are possible and sets them up, but the router decides which ones to activate.

提交回复
热议问题