【问题标题】:Passing PHP variable as prop to Vue tab component将 PHP 变量作为道具传递给 Vue 选项卡组件
【发布时间】:2019-02-08 16:42:12
【问题描述】:

我正在尝试将 PHP 变量 $avail 作为道具传递给我的 Vue 组件 ComponentHome。

以下是我的代码的简化版本。在我的页面上,“avail”变量似乎是未定义的,因为“Availability:”后面的空格是空白的。我尝试过使用 v-bind:avail="{{ $avail }}",但是我的组件都没有加载。为什么是这样?是否存在问题,因为只有一个选项卡组件使用此变量?还是我没有正确通过?

更多信息:我已经测试了 PHP 变量 $avail 的设置是否正确。 Vue 导航栏本身也不应该成为问题,因为它之前运行良好。

index.php

<?php $avail = "Coming soon"; ?>

<!--navigation bar begin-->
  <nav class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <div class="collapse navbar-collapse" id="myNavbar">
        <ul class="nav navbar-nav" data-toggle="collapse" data-target="#myNavbar">
          <li class="clickable"
            avail="{{ $avail }}"
            v-for="tab in tabs"
            v-bind:key="tab"
            v-bind:class="[{ active: currentTab === tab }]"
            v-on:click="currentTab = tab"
          ><a>{{ tab }}</a></li>
        </ul>
      </div>
    </div>
  </nav>
  <!--navigation bar end-->

<!--tab content begin-->
  <keep-alive><!--to cache inactive components-->
    <component v-bind:is="currentTabComponent"></component>
  </keep-alive>
<!--tab content end-->

app.js

var ComponentHome = {
    template:
    '<div class="container">\
        <h3>Availability: {{ avail }}</h3>\
    </div>',
    props: ['avail'],
    data: function() {
        return {
            avail: this.avail
        }
    }
}

var vm = new Vue({
  el: "#content",
    components: {
        "tab-home" : ComponentHome,
        "tab-costsandamenities" : ComponentCosts,
        "tab-photos" : ComponentPhotos,
        "tab-application" : ComponentApplication
    },
  data: {
    currentTab: "Home",
    tabs: ["Home", "Costs and Amenities", "Photos", "Application"]
  },
  computed: {
    currentTabComponent: function () {
      return "tab-" + this.currentTab.replace(/ /g ,"").toLowerCase();
    }
  }
})

【问题讨论】:

  • 也许 &lt;script&gt;window.variables = &lt;?php echo json_encode($avail); ?&gt;&lt;/script&gt; 然后它在全球范围内可用。

标签: php vue.js vue-component prop


【解决方案1】:

由于$avail 是一个 PHP 变量,您需要使用 PHP 来呈现它。

avail="{{ $avail }}" 替换为avail="&lt;php echo $avail; ?&gt;"

您还需要在示例顶部使用正确的结束标记。 php?&gt; 不是有效的结束标记。

【讨论】:

  • 谢谢!我可以看到该变量现在已在 HTML 中正确加载(它显示为 '
  • ') 但页面上仍未加载文本。
  • 您需要将数据传递给您的子组件。我想,你可以这样做: 还要确保你没有声明数据属性与道具名称相同的名称。您可以移除整个数据:ComponentHome 中的 {} 部分。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签