dongshadu4498 2019-06-19 21:39
浏览 152
已采纳

将PHP变量传递给vue.js vue组件

I am working on a wordpress site where I need to pass a php string variable to a .vue component so that one of the vue variable will reflect the value of the php varaible

index.php

<?php 
$foo = 72;
?>

<div id='app'></div>

app.js

import App from './views/App';
new Vue({
  el: '#app',
  render: h => h(App)
});

./views/App.vue

<template>
<h1>{{ foo }}</h1>
</template>

<script>
export default {
name: 'App',
 data() {
  return {
   foo: ''
  }
 }
}
</script>

<style></style>

As you can see in index.php, $foo = 72. I want that 72 value will be pass on to $foo in App.vue

  • 写回答

1条回答 默认 最新

  • dongwang6837 2019-06-20 02:35
    关注

    In the context of WordPress, you would call wp_localize_script with the required data so that it becomes available in the global space of the script that initializes your Vue.js application.

    Assuming you have registered vue-script beforehand:

    <?php
    $foo = 42;
    wp_localize_script('vue-script', 'foo', $foo);
    wp_enqueue_script('vue-script');
    

    Then in the script you could use propsData to pass down foo when creating the Vue instance:

    import App from './views/App';
    new Vue({
      el: '#app',
      render: h => h(App),
      propsData: { foo }
    });
    

    ...then replacing data with props in App.vue:

    <script>
    export default {
      name: 'App',
      props: ['foo'],
    }
    </script>
    

    I haven't tested this myself, so YMMV but this is basically how you should approach this. Providing a little more context could point to other solutions, like ready-made Vue.js / WordPress frameworks such as Gridsome or NuePress

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中mjs用不了
  • ¥15 Ios抖音直播的时候如何添加自定义图片在直播间!
  • ¥60 riscv-pulpino总线上挂载axi从机
  • ¥15 ssh登录页面的问题
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥15 stm32 串口通讯过程中的问题
  • ¥20 公众号如何实现点击超链接后自动发送文字