问题
In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states
with my {{ $jobs }}
variable. I need to list all Job Titles as an array.
In my controller I have
$jobs = Job::all(['job_title']);
I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?
I have tried, in my.js
var jobs = {{ $jobs }}
But that wont work.
回答1:
For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:
var jobs = JSON.parse("{{ json_encode($jobs) }}");
Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready
is the answer to that)
<script>
var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>
If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.
回答2:
This works for me
jobs = {!! json_encode($jobs) !!};
回答3:
Just to add to above :
var jobs = JSON.parse("{{ json_encode($jobs) }}");
will return escaped html entities ,hence you will not be able to loop over the json object in javascript , to solve this please use below :
var jobs = JSON.parse("{!! json_encode($jobs) !!}");
or
var jobs = JSON.parse(<?php echo json_encode($jobs); ?>);
回答4:
this approach work for me:
var job = {!! json_encode($jobs ) !!}
and use in java script
回答5:
in laravel 6 this works for me
using laravel blade directive
var jobs = {!! json_encode($jobs) !!};
also used @json
directive
var jobs = @json($jobs);
using php style
var jobs = <?php echo json_encode($jobs); ?>
回答6:
I just solved this by placing a reference on the window
Object in the <head>
of my layout file, and then picking that reference up with a mixin that can be injected into any component.
TLDR SOLUTION
.env
GEODATA_URL="https://geo.some-domain.com"
config/geodata.php
<?php
return [
'url' => env('GEODATA_URL')
];
resources/views/layouts/root.blade.php
<head>
<script>
window.geodataUrl = "{{ config('geodata.url') }}";
</script>
</head>
resources/js/components/mixins/geodataUrl.js
const geodataUrl = {
data() {
return {
geodataUrl: window.geodataUrl,
};
},
};
export default geodataUrl;
usage
<template>
<div>
<a :href="geodataUrl">YOLO</a>
</div>
</template>
<script>
import geodataUrl from '../mixins/geodataUrl';
export default {
name: 'v-foo',
mixins: [geodataUrl],
data() {
return {};
},
computed: {},
methods: {},
};
</script>
END TLDR SOLUTION
If you want, you can use a global mixin instead by adding this to your app.js
entrypoint:
Vue.mixin({
data() {
return {
geodataUrl: window.geodataUrl,
};
},
});
I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window
Object.
I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl"
and see everything you need to understand how and why the code is working.
That consideration is important if the code may live for a long time and another developer may come across it.
However, JavaScript::put([])
is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.
Imagine you have some Vue code that is consuming window.chartData
that came from JavaScript::put([ 'chartData' => $user->chartStuff ])
. Depending on the number of references to chartData
in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData
work, especially if you didn't write that code and the next person has no idea JavaScript::put()
is being used.
In that case, I recommend putting a comment in the code like:
/* data comes from poop.php via JavaScript::put */
Then the person can search the code for "JavaScript::put"
and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.
It is always a good idea to use Vue component prop declarations like this:
props: {
chartData: {
type: Array,
required: true,
},
},
My point is, if you use JavaScript::put()
, then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.
I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.
In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:
routes/web.php
Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');
app/Http/Controllers/UserController.php
public function getChart(Request $request, User $user)
{
// do stuff
$data = $user->chart;
return response()->json([
'chartData' => $data,
]);
}
Anywhere in Vue, especially a created lifecycle method:
created() {
this.handleGetChart();
},
methods: {
async handleGetChart() {
try {
this.state = LOADING;
const { data } = await axios.get(`/charts/${this.user.id}/coolchart`);
if (typeof data !== 'object') {
throw new Error(`Unexpected server response. Expected object, got: ${data}`);
}
this.chartData = data.chartData;
this.state = DATA_LOADED;
} catch (err) {
this.state = DATA_FAILED;
throw new Error(`Problem getting chart data: ${err}`);
}
},
},
That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.
I'd recommend using such states as computed props:
computed: {
isLoading() { return (this.state === LOADING); },
isDataLoaded() { return (this.state === DATA_LOADED); },
isDataFailed() { return (this.state === DATA_FAILED); },
},
With markup such as:
<div v-show="isLoading">Loading...</div>
<v-baller-chart v-if="isDataLoaded" :data="chartData"></v-baller-chart>
<button v-show="isDataFailed" type="button" @click="handleGetChart">TRY AGAIN</button>
来源:https://stackoverflow.com/questions/29308441/using-javascript-to-display-laravels-variable