【问题标题】:How to init Vuejs + VueRouter on certain pages within Laravel如何在 Laravel 中的某些页面上初始化 Vuejs + VueRouter
【发布时间】:2017-05-01 04:56:18
【问题描述】:

为了更好地解释它,我正在使用 Laravel 后端创建一个应用程序(用于学习目的),并且我也在尝试很多东西。但我只想创建一两个页面来运行 vue/vue-router 来显示某些组件。就像多页网站,其中包含很少的单页应用程序。

我剪得很粗

<div id="{{ (Route::current()->getName() == 'vue-page1') ? 'app' : '' }}">
    @yield('content')
</div>

但这不是解决方案我尝试使用 JS 限制之后的页面

if (!document.getElementById("app"))

不明白,Vue 还是启动了。我想保留当前结构,只是为了阻止它在不应该初始化的页面上进行初始化。

【问题讨论】:

  • 张贴app.js 文件中您正在加载内容的部分。如果它是默认的,您应该查看bootstrap.js 文件并在那里进行更改并在您使用的情况下注册 vue 和 vue-router。
  • 只有在必要时才尝试加载 vue 路由器,例如 document.getElementById("app") 为真时

标签: laravel laravel-5 vue.js vue-router


【解决方案1】:

根据您发布的代码,尝试预先构建选项对象,而不是将其传递给new Vue 实例。像这样:

let options = {
    el: '#app',
    name: 'app',
    render: app => app(App),
    data: {
        a: 1
    },
    created: function () {
        // `this` points to the vm instance
        console.log('a is: ' + this.a)
    },
    mounted() {
      console.log('done');
      auth.check()
    }
}
if(document.getElementById("app-with-routes"))//yaah we have app with routes
{
    window.VueRouter = require('vue-router');
    let router = new VueRouter({
        routes: [
            {
                path: '/',
                name: 'home',
                component: Vue.component('home', require('./components/Home.vue'))
            },
            // .... all the routes you need
            ]});
    options['router'] = router
}

const app = new Vue(options);

这样你就可以使用所有的 vue sweet 部分,而无需处理路由器。

【讨论】:

  • 太好了,我刚刚将const app = new Vue(options); 移到了if
  • @Developer 在我的回答中,我将大部分内容移到了 if 中,因为您可能想将一些 vue 糖果用于其他页面。例如v-if v-else 显示/隐藏基于属性的元素。
【解决方案2】:

您是否尝试过仅在需要的页面中包含 vue.js?

@section('styles')
{{ (Route::current()->getName() == 'vue-page1') ? '<script src="https://unpkg.com/vue/dist/vue.js"></script>' : '' }}
@endsection

【讨论】:

  • Webpack 正在运行,所以这也不是一个选项。我正在尝试保持当前结构并在 js 或 Vue 中解决
猜你喜欢
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多