【问题标题】:Use PhP Variavle in Vue js component在 Vue js 组件中使用 PhP 变量
【发布时间】:2021-09-30 13:03:12
【问题描述】:

我开始在我现有的 PhP 项目中集成一些 Vue 3 组件。

代码如下例所示

phpfile.php

<?php
//..get some User and Session Data
//.. get some other fancy data from DB
$data = array(
'userData' => $userdata,
'otherData' => $otherData
);
include 'template.php';
?>

模板.php

<html>
<head>
<script>Link to vue js CDN</script>
<-- Head stuff -->
</head>
<body>
<div id="vueApp">
<div v-if="isAdmin"> <-- show some Admin things --></div>
<div v-else> <-- show some not Admin things --></div>
</div>
<script src="../vueComponent.js"></script>
</body>
</html>

vueComponent.js

const app = Vue.createApp({
    data() {
    return {
           isAdmin: false,
           }
    },
methods: {

    
},
mounted() {
    
}
})
app.mount('#vueApp')

如何将 $data['userdata'] 放入 vue 组件中?

感谢您的帮助。

【问题讨论】:

  • 将其作为道具传递或将其作为 API 端点,组件可以从中调用数据并填充组件数据
  • 嗨,我不想编写额外的 api 来获取我已经为加载页面而获取的相同数据。那么,我如何将它们作为 pro 传递给组件? js 文件中的 不起作用
  • 你不能是我这么说的原因,至少在你想要的上下文中

标签: php vuejs3


【解决方案1】:

在调用组件之前将数据放在文档上。

<script>const data = <?= json_encode($data); ?></script>
<script src="../vueComponent.js"></script>

然后将其传递给组件:

const app = Vue.createApp({
  data() {
    return {
      isAdmin: data.userData.isAdmin,
    }
  },
...

你也可以在like之后设置:

app.isAdmin = data.userData.isAdmin

【讨论】:

  • imo、vue 和 php 很丑,用 nuxt 重写你的应用程序,然后通过 nuxtServerInit 在 vuex 存储中设置数据
  • 谢谢!我会尝试这种方式。 @Lawrence我对nuxt没有经验。我还在学习使用 vue 来改进我的前端,并且可能会用它来重建整个项目。但我会看看 nuxt。
猜你喜欢
  • 2020-04-18
  • 2021-03-08
  • 2019-11-18
  • 1970-01-01
  • 2017-07-08
  • 2019-05-05
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
相关资源
最近更新 更多