如何在 Vue.js 模板文字中使用 php 变量?

问题描述

我正在使用 Laravel 和 Vue.js。所以在刀片模板中,我想在 Vue.js 组件模板中使用 PHP 变量。所以我尝试了下面的代码

Vue.component('add-edit-card',{
        data: function() {
            return {
                topt : `{!! $types !!}`
            }
        },template: ` <select id="component-type" class="form-control">
                                        <option>Select</option>
                                        @{{topt}}
                                        </select>`,props: ['value'],});

现在在 HTML 输出中,选项显示为单独的字符串。不像 HTML。如何解决这个问题?

enter image description here

解决方法

Vue 的 string interpolation(即 {{ topt }})将字符串解释为纯文本,因此渲染将显示原始 HTML。

由于您实际上并不需要 HTML 作为数据变量,您可以直接将 PHP 变量插入到组件的 template 选项中:

Vue.component('add-edit-card',{
  template: `<select id="component-type" class="form-control">
               <option>Select</option>
               {!! $types !!} ?
             </select>`
});