I’ve created this page template for integrating a vue app into an existing website
<?php
/*
* Template Name: Registration Form
*/
get_header();
?>
<div id="app"></div>
<?php
get_footer();
?>
After a bit of debugging I’ve solved a problem with vue router that wasn’t loading the views for my app due to the base url that I need to set manually.
In my vue app I will have a custom login and registration form that I need to handle in wordpress. To achive this I want to use axios in the vue app to make requests and pass the data to wp.
I’ve readed about admin-ajax.php
but I’m a bit confused on how to make it working with vue. In the wordpress documentation it’s suggested to use wp_localize_script()
fuction to pass the admin url to the script that will need it.
I have created a simple function in the functions.php
file
function setup_ajax_vue(){
wp_register_script('vue-js', get_template_directory_uri() . '/dist/assets/index.js', array(), false, true );
wp_enqueue_script('vue-js');
wp_register_script('vue-css', get_template_directory_uri() . '/dist/assets/index.css');
wp_enqueue_style('vue-css');
}
add_action('wp_enqueue_scripts', 'setup_ajax_vue');
In this function that I will move into a plugin, I’m loading at the moment, only the vue app files. How I can integrate the ajax handler correctly to let the vue app send ajax request to process the forms data?
2
Answers
Added somewhere in your page this code before your ajax call.
So then you can:
Or of course using axios or fetch.
wp_localize_script function is often used to pass generic data from PHP to JavaScript.
In simple words, if you have to pass some data from php to Javascript, WordPress later add a new function
wp_add_inline_script
butwp_localize_script
is better when you’re registering a script.This function needs 3 args:
so in your code, you’ll localize the php data with your registered script by the above code.
Note: you need to register the script first and then localize it.
in the above code, we have used the js object name
vue_js_params
and we’ve passedajaxurl
in the data.so in your js code, you can access it using
vue_js_params.ajaxurl
it will be globally available to be used.If you don’t know how to register an ajax callback in WordPress then you can learn it from tutorials, I am sure there will many google article on "How to use ajax in WordPress"