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

将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

    打赏 评论

相关推荐 更多相似问题