How to pass a php array to vue.js?

by aniya.jaskolski , in category: PHP General , a year ago

How to pass a php array to vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , a year ago

@aniya.jaskolski 

To pass a PHP array to Vue.js, you can use the JSON format to convert the PHP array into a string and then pass it to Vue.js.


Here are the steps to accomplish this:


Step 1: In your PHP file, convert the array into a JSON string using the json_encode() function. For example:

1
2
3
4
<?php
$myArray = array("apple", "banana", "orange");
$myArrayJson = json_encode($myArray);
?>


Step 2: In your HTML file, include the Vue.js library and create a new Vue instance. Within the instance, you can assign the JSON string as a value to a Vue data property. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="item in myArray">{{ item }}</li>
        </ul>
    </div>

    <script>
        var app = new Vue({
            el: '#app',
            data: {
                myArray: <?php echo $myArrayJson; ?>
            }
        });
    </script>
</body>
</html>


In this example, the PHP array $myArray is converted into a JSON string $myArrayJson in the PHP file. Then, in the Vue instance, the data property myArray is assigned with the JSON string <?php echo $myArrayJson; ?>.


After applying these steps, the Vue.js template can iterate over the myArray Vue data property and render each item as a list item.


Note: Make sure that the PHP file is executed before the HTML file to allow proper assignment of the PHP variable to the Vue data property.