2

Is it advisable passing some nonsensitive data to vue within an inline script?

HTML

<script>
    var foo = <?php echo $foo ?>
</script>

Vue.js

new Vue({
    data: { 
        foo: foo 
    }
});
1
  • 2
    Yea this is fine, you could even just put the php echo directly in the Vue data. Make sure your variable isn't a common name though, global namespace and all Commented Apr 29, 2016 at 13:38

2 Answers 2

2

This is probably a bit opinionated, but I'd avoid using a global variable like that in an application. Instead, I'd make use of HTML5 data- attributes and store useful bits of data the frontend needs in them.

You can do something like this:

<body data-my-thing='{"foo": "bar", "baz": true}'>

The above example uses JSON, what I'd normally do is use json_encode in a controller or view composer and just echo out the string like so (since we're using Balde here, the JSON is automatically escaped):

<body data-my-thing='{{ $myJson }}'>

If you were just using plain PHP then you should escape the JSON like this:

<body data-my-thing='<?=htmlspecialchars($myJson) ?>'>

Of course, you don't need to JSON, if it's more appropriate you can just store a plain string or number in there. It depends on the needs of your application.

To grab the value from your data attribute you'd just use the following JavaScript:

document.body.getAttribute('data-my-thing');

And if you've made use of JSON, don't forget to decode it!

JSON.parse(document.body.getAttribute('data-my-thing'));
Sign up to request clarification or add additional context in comments.

2 Comments

You'll probably want to htmlspecialchars() JSON used in this manner.
There's no need to use htmlspecialchars in a Blade template - everything is automatically escaped.
0

I used to use data- attributes to bootstrap data, but I kept running into issues involving quotes.

Say that this:

<body data-my-thing='{{ $myJson }}'>

Evaluates to this:

<body data-my-thing='{"foo": "bar", "baz": true}'>

No big deal. What if your data looks like this?

<body data-my-thing='{"foo": "bar's", "baz": true}'>

Suddenly you have an issue. That's why I've used the script solution that the original poster mentioned above.

2 Comments

htmlspecialchars() is made for solving that.
Would you mind posting a solution that used that? I'm not from the PHP world so my experience is more general. (Though the issue I mentioned above did bite me in production.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.