首页 > 解决方案 > 在 Vue js 组件中使用 PhP Variavle

问题描述

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

代码类似于以下示例

php文件.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 组件?

谢谢你的帮助。

标签: phpvuejs3

解决方案


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

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

然后将其传递给组件:

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

你也可以设置如下:

app.isAdmin = data.userData.isAdmin

推荐阅读