首页 > 解决方案 > 如何让子挂载首先在 vue-router 异步加载组件中触发?

问题描述

我正在使用 vue/vue-router 加载网站。这是演示该问题的代码。

<!DOCTYPE html>
<html>
    <head>
        <title>Title of the document</title>
        <script src="https://unpkg.com/vue"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.6/vue-router.min.js"></script>
    </head>
    <body>
        <div id="app">
            <router-view></router-view>
        </div>
        <script>
            Vue.component('a-a', function(resolve, reject) {
                setTimeout(function() {
                    resolve({
                        template : "<div>A</div>",
                        mounted : function() {
                            alert(1);
                        }
                    });
                }, 2000);
            });
            new Vue({
                el: '#app',
                router : new VueRouter({
                    mode: 'history',
                    routes: [
                        { path: '/foo', component: Vue.component("a-a") }
                    ]
                }),
                mounted : function() {
                    alert(2);
                }
            });
        </script>
    </body>
</html>

我修改了 IIS 以允许 REST 样式的链接像这样返回上面的页面

<rewrite>
  <rules>
    <rule name="SPA Routes" stopProcessing="true">
      <!-- match everything by default -->
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <!-- unless its a file -->
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <!-- or a directory -->
        <!--<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />-->
        <!-- or is under the /api directory -->
        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
        <!-- list other routes or route prefixes here if you need to handle them server side -->
      </conditions>
      <!-- rewrite it to /index.html -->
      <action type="Rewrite" url="App/test2.html" />
    </rule>
  </rules>
</rewrite>

当我访问该页面时,我使用链接/App/test2.html/foo,它返回上面的页面。

然后我期望vue-router根据url路径加载组件,然后异步加载组件,等待resolve函数,然后在child上运行mounted函数,最后在parent上运行mounted函数。所以基本上是警报 1,然后是 2。但是父母先警报,所以它是 2,然后是 1。

我怎样才能让孩子先上马?

谢谢

标签: javascriptvue.jsvue-router

解决方案


推荐阅读