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

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料