Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using VueJS with a PHP Variable

Tags:

vue.js

I'm attempting to bind a HTML element which contains a string echoed via PHP so that I can use it with VueJS. Essentially what I am going to be doing is switching between GBP and USD depending on some php/mysql database queries (USD is default value). Here is a simplified example of what I have tried so far.

<div id="app">
   <?php $string = 'GBP'; ?>
   <!-- Hide this from the front end but bind to Vue somehow -->
   <span v-el:currency style="display: none;"><?php echo $string; ?></span>

   <p>Payment currency: {{ currency }}</p>
</div>

Of course I could just echo the php variable again, but the main reason I want to bind it to a VueJS element is so I can use the value of this element in my JS to do something like this...

if (this.currency === 'GBP') {
   return "Paying in GBP";
} else {
   return "Paying in USD";
}

Worth noting that I already have a fair bit of VueJS working within this #app so it's nothing to do with the configuration of Vue being wrong, more a case of just not knowing the correct way to approach the issue.

like image 256
GuerillaRadio Avatar asked Jan 05 '23 18:01

GuerillaRadio


1 Answers

I would not interleave PHP and javascript inside a component. Why don't you create a new script at the end with the variables you need?

<!-- bottom of the body -->
<script>var currency = <?php echo $yourVar; ?></script>

And then it will be a global variable and you just take it from there.

like image 183
gurghet Avatar answered Jan 23 '23 05:01

gurghet