首页 > 解决方案 > 将 PHP 变量作为道具传递给 Vue 选项卡组件

问题描述

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

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

更多信息:我已经测试了 PHP 变量 $avail 的设置是否正确。Vue 导航栏本身也不应该是一个问题,因为它以前工作得很好。

索引.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-->

应用程序.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();
    }
  }
})

标签: phpvue.jsvue-componentprop

解决方案


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

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

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


推荐阅读