DEV Community

Discussion on: Using Vue in WordPress

Collapse
 
mzerterungwa profile image
mzerterungwa

Thank you for the post Lisa. How can I pass a wordpress PHP variable from wp-vue-tutorial.php into the vue app instance in vuecode.js?

Collapse
 
workingwebsites profile image
Lisa Armstrong


Hmmm, very good question!

Two things to remember:

  1. PHP writes the HTML file on the server side. That file is passed to the browser where the JavaScript is run.
    That means you need to output the PHP variable so it shows up in the HTML file in the browser. Then Javascript can deal with it. A simple $your_var in the right place will do.

  2. Vue is just Javascript and your Vue code is really a Javascript object.
    That means (generally) you can access it anywhere within JavaScript.

In the example, the object is called 'app'

var app = new Vue({
...
})

That means 'app' can be accessed on the Javascript level.
If you were to run ' console.log(app) ' you would see the object, it's data etc.

Therefore, you could change a value in ' app ' from the Javascript level.

Something like:


 app.message = 'Bonjour Vue';

That means, if you can output something like:


 app.message = '[ php var here ] Vue';

It should work.

The trick is where to add the code in the WordPress platform.

In this example, you're outputting the div, so try adding it there.

Try:

function func_wp_vue(){
  //Add Vue.js
  wp_enqueue_script('wpvue_vuejs');
  //Add my code to it
  wp_enqueue_script('my_vuecode');

  $message = 'Bonjour Vue';

   //Add script 
  $str=""
   ."app.message = 'Bonjour Vue'"
   ."";

  // Display the results
  $str .= ""
    ."Message from Vue: {{ message }}"
    .""

  //Return to display
  return $str;
} // end function

I wouldn't be surprised if WordPress has an issue with a script tag in the middle of things, but try it and see if it works.

Let me know how it turns out. I'm curious to see how this can work.

Collapse
 
oglenas profile image
Jon Dewitt

A bit late, but I believe the correct solution to this question would be to utilize wp_localize_script, which lets you pass php values to a given script.

developer.wordpress.org/reference/...
pippinsplugins.com/use-wp_localize...