@proviruz

Как заставить vuejs перезагрузить компонент?

В наличии такой компонент:

var testComponent = Vue.component('main-section', (resolve) => {
            axios.post('/test.php').then( (res) => {
                resolve({ 
                    template: res.data,
                    mounted: () => {
                        console.log('mounted-' + new Date().getTime());
                    }
                });
            });
        });

Также роутер:

var router = new VueRouter({
   routes: [
{ path: '/foo', component: testComponent }, 
{ path: '/bar', component: testComponent },
{ path: '*', component: testComponent }],
   mode: 'history'
});

<router-link to="/foo"></router-link>
<router-link to="/bar"></router-link>
<router-link to="/somelink"></router-link>
<section class="content">
        <router-view :key="$route.fullPath"></router-view>
</section>

Суть проблемы - компонент загружает шаблон только один раз, в дальнейшем при изменении адреса страницы,
mounted срабатывает, но сам компонент не перерисовывается, то есть не делает ajax запрос на сервер. По сути ситуация такая - необходимо чтобы в router-view подгружался разный шаблон, в зависимости от пути. Возможность создавать под каждый роут отдельный компонент не подходит, ибо пути динамические и сервер по каждому пути отдает разное содержимое. Да и сами роуты также заранее неизвестны. В общем, когда я кликаю по ссылкам, console.log('mounted-' + new Date().getTime()) срабатывает, но новый шаблон с сервера не подгружается.
  • Вопрос задан
  • 2152 просмотра
Решения вопроса 1
potapchino
@potapchino
//App.vue

<template>
  <div id="app">
    <router-link to="/random/12323jlwe">12323jlwe</router-link>|
    <router-link to="/random/cxz98c7zf8a">cxz98c7zf8a</router-link>|
    <router-link to="/random/90cvuiwa-r">90cvuiwa-r</router-link>
    <section class="content">
      <router-view :key="$route.fullPath"></router-view>
    </section>
  </div>
</template>


//main.js

import Vue from "vue";
import Router from "vue-router";
import App from "./App.vue";

Vue.use(Router);

var testComponent = Vue.component("main-section", {
  template: `<component :is="template"></component>`,
  data() {
    return {
      template: Vue.compile("<div>please stand by</div>")
    };
  },
  created() {
    // axios.post...
    setTimeout(() => {
      this.template = Vue.compile(`<div>${this.$route.fullPath}</div>`);
    }, 2000);
  },
  mounted() {
    console.log("mounted-" + new Date().getTime());
  }
});

const router = new Router({
  mode: "history",
  routes: [{ path: "/random/:random", component: testComponent }]
});

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  render: h => h(App)
});


https://codesandbox.io/s/50v0xwyzv4
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы