将vue变量安装在section('title')上

时间:2019-02-16 12:19:13

标签: laravel vue.js laravel-blade

我在刀片模板上显示vue变量时遇到问题

我的布局/master.blade.php

<html>
    <head>
        <title>@yield('title') | My company</title>
.....

news.blade.php

@extends('layouts.master')

<div id="pagetitle">
@section('title', @{{pagetitle}} )
</div>

@section('content')
....
@endsection

resources / js / news.js

new Vue({

    el: '#pagetitle',

    data: {
        pagetitle:'',
    },

    mounted() {
        this.fetchArticlesPage();
    },

    methods: {
        fetchArticlesPage(page_url) {
            page_url = '/api/articles/news';
            fetch(page_url)
            .then(res => res.json())
            .then(res => this.pagetitle = res.page_title)
            .catch(err => console.log(err));
        },

    }
});

,并使用jsonResource从控制器获取此响应数据

{
 "links": {
    "first": "http://localhost:8000/api/articles/news?page=1",
    "last": "http://localhost:8000/api/articles/news?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://localhost:8000/api/articles/news",
    "per_page": 3,
    "to": 3,
    "total": 3
  },
  "page_title": "News"
}

我的语法错误出乎意料的{

如果我像这样穿上@section('content')

@section('content')
   <div id="pagetitle">
     @{{pagetitle}}
   </div>
@stop

它很好,将显示“新闻”数据, 请帮助,是vue和laravel编程的新功能

2 个答案:

答案 0 :(得分:0)

Blade模板指令在服务器中处理,并将响应发送到客户端。

此后,将在浏览器中处理Vue模板指令。

在该帐户上,后面的带有 Vue胡子的示例按预期方式工作,因为下面的块作为整体响应内容的一部分发送到浏览器。

   <div id="pagetitle">
     {{pagetitle}}
   </div>

然后在浏览器中运行的Vue程序运行,并在此模板中插入变量。

对于前一个示例,

@section('title', @{{pagetitle}})

由于第二个参数未以字符串形式给出,因此当服务器尝试编译该节时将在服务器中导致错误。

可以通过引用逃逸的 Vue胡子来纠正此错误。

@section('title', '@{{pagetitle}}')

编辑{{pagetitle}} 未编译位于文档标题中

创建的Vue实例安装在主体中包含的元素上。因此,仅在安装Vue实例的元素的文档树上进行编译。

我建议创建一个单独的Vue实例来管理文档的头部。例如

const helmet = new Vue({
    el: 'head',
    data: {
        pagetitle:'',
    },

    mounted() {
        this.fetchArticlesPage();
    },

    methods: {
        fetchArticlesPage(page_url) {
            page_url = '/api/articles/news';
            fetch(page_url)
            .then(res => res.json())
            .then(res => this.pagetitle = res.page_title)
            .catch(err => console.log(err));
        },

    }
})

答案 1 :(得分:0)

你可以尝试

@section('title',@pagetitle)