简体   繁体   English

在Laravel上异步加载Vue组件

[英]Load Vue components async on Laravel

I have some javascript to run in a blade file but it is waiting for a Vue component to fully load before running. 我有一些可在blade文件中运行的javascript ,但是它正在等待Vue组件完全加载后再运行。

...
<p id="a"></p>
<my-vue-component></my-vue-component>
...
<script>
  document.getElementById('a').innerText = 'ggg'
</script>

The javascript code waits for the Vue component to load and then it executes. javascript代码等待Vue组件加载,然后执行。

I don't want the Vue component pausing the rest of the javascript. 我不希望Vue组件暂停其余的javascript。 I want it to load while the rest of the javascript executes or to load after the javascript finishes executing. 我希望它在其余javascript执行时加载,或者在javascript完成执行后加载。

I tried installing the dynamic import plugin for async rendering 我尝试安装用于异步渲染的动态导入插件

npm install --save-dev @babel/plugin-syntax-dynamic-import

and registering it in .babelrc 并在.babelrc中注册

{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

and running the compiler 并运行编译器

npm run watch

And then in the app.js where the components are registered 然后在app.js中注册组件

Vue.component('my-vue-component', () => import('./components/MyVueComponent.vue').default);

That didn't do what I was expecting 那没有达到我的期望

If the javascript you want to load before or during the loading of vue components is related to the vue component itself, then go for the solution posted by @matticusatrd. 如果要在加载vue组件之前或期间加载的javascript与vue组件本身有关,请使用@matticusatrd发布的解决方案。 If you want the javascript executed before loading any vue components, place it in the <head> of your page before your app.js . 如果要在加载任何vue组件之前执行javascript,请将其放在app.js之前页面的<head>中。

Beware, this will make the entire page load wait for the javascript code to execute. 当心,这将使整个页面加载等待javascript代码执行。 Additionally you won't have the dom available yet, so you might need to listen to an event like DOMContentLoaded before doing any manipulations to the page. 另外,您还没有可用的dom,因此您可能需要在对页面进行任何操作之前先听DOMContentLoaded类的事件。

To run some JavaScript after a Vue component is loaded, you can simply add it to the mounted() method. 要在加载Vue组件后运行一些JavaScript,只需将其添加到mounted()方法中即可。

export default {
    name: "MyVueComponent",
    ...
    mounted() {
        // everything here runs after the component is loaded
        let a = true;
    }
}

Well, It will not wait because vue js compile and then generate DOM. 好吧,它不会等待,因为vue js会编译然后生成DOM。 A better way to perform any action after vue js load is to use the mounted or created methods of Vue Component class. 在vue js加载后执行任何操作的更好方法是使用Vue Component类的已安装或创建的方法。

export default{
    name: 'TestComponent',
    mounted(){
        //
    },
    created(){
        //
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM