(Vue.js) Same component with different routes

后端 未结 3 1162
别跟我提以往
别跟我提以往 2020-12-16 12:53

I would like to use the same component for different routes in a Vue.js application.

I currently have something like this:


main.js

相关标签:
3条回答
  • 2020-12-16 13:17

    You can use watch property, so your component will not waste time to reloading:

    index.js You might have something like this

    const routes = [
      {
        path: '/users/:id',
        component: Vue.component('user', require('./comp/user.vue').default)
      }
    ]
    

    user.vue

    created(){
      // will fire on component first init
      this.init_component();
    },
    watch: {
      // will fire on route changes
    //'$route.params.id': function(val, oldVal){ // Same
      '$route.path': function(val, oldVal){
        console.log(this.$route.params.id);
        this.init_component();
      }
    },
    methods: {
      init_component: function(){
        // do anything you need
        this.load_user_data_with_ajax();
      },
    }
    
    0 讨论(0)
  • 2020-12-16 13:18

    This is expected behaviour as Vue is trying to be optimal and reuse existing components. The behaviour you want to achieve used to be solved with a setting called canReuse, but that has been deprecated. The current recommended solution is to set a unique :key property on your <router-view> like so:

    <router-view :key="$route.path"></router-view>
    

    Check out this JSFiddle example.

    0 讨论(0)
  • 2020-12-16 13:24

    Just to make a note. If anybody is working with SSR template, things are a bit different. @mzgajner's answer does indeed recreate the component but will not trigger the asyncData again.

    For that to happen, modify entry-client.js like this.

    OLD:

    const activated = matched.filter((c, i) => {
        return diffed || (diffed = (prevMatched[i] !== c))
    })
    

    NEW:

    const activated = matched.filter((c, i) => {
    
        /*
            In my case I only needed this for 1 component
        */
    
        diffed = ((prevMatched[i] !== c) || c.name == 'p-page-property-map')
    
        return diffed
    })
    
    0 讨论(0)
提交回复
热议问题