将PHP变量作为prop传递给Vue选项卡组件

时间:2018-09-03 15:46:35

标签: php vue.js vue-component prop

我试图将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();
    }
  }
})

1 个答案:

答案 0 :(得分:2)

由于$avail是一个PHP变量,因此您需要使用PHP进行渲染。

avail="{{ $avail }}"替换为avail="<php echo $avail; ?>"

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

相关问题