混合PHP值和VueJS值

时间:2017-04-24 14:05:06

标签: vue.js

我在一个小项目上工作,我正在使用VUEJS和PHP支持到Wordpress。

<div v-if="ent.Account === 'username' " v-for="ent in leaders">
hey there {{ ent.Name }} welcome back!
</div>

我希望“用户名”等于来自wordpress的当前登录用户

<?php $current_user->user_login ?>

2 个答案:

答案 0 :(得分:0)

试试这个:

<div v-if="ent.Account === '<?php $current_user->user_login ?>' " v-for="ent in leaders">
hey there {{ ent.Name }} welcome back!
</div>

答案 1 :(得分:0)

VueJS是仅客户端库,而PHP是服务器端。您无法直接混合内容,但是由于您使用的是wordpress,因此可以“本地化”您的JavaScript。

如果您使用的是webpack或browserify之类的工具,则应本地化捆绑的app.js和/或chunk-vendor.js,否则,您可以直接本地化vue.js,就像这样(假设您正在工作)主题)

在您的functions.php中,编写

function my_enqueue_scripts() {

    wp_enqueue_script(
        'my_js_script_handle',
        get_template_directory_uri() . 'js/app.js', // <<---- your Vue bundled code
        array(),
        false,
        true // <<--- Enqueue in footer
    );

    /**
     * Add initial data to your Vue JS object.
     *
     * @var array
     */
    $data = array(
        'currentWpUser' => wp_get_current_user()->user_login,
    );

    wp_localize_script( 'my_js_script_handle', 'PhpDataObject', $data ); // <<--- localize your script

}

add_action ('wp_enqueue_scripts', 'my_enqueue_scripts');

并在客户端javascript中使用PHP生成的数据,如下所示(假设您正在使用vue-cli或vueify之类的工具)

<div id="app">
    <p>hey there {{ currentWpUser }} welcome back!</p>
</div>

new Vue({
    el: '#app',
    data: {
        currentWpUser: PhpDataObject.currentWpUser
    }
});