Laravel & VueJS - questions - laravel

I am new to VueJS.
Let's assume that I plan to create an extensive application. And for example I have 3 separate pages: mypage.com/account, mypage.com/players, mypage.com/orders. Each page has its own controller and in it I return a file with a view (account.blade.php etc.) and pass parameters in variables. Then in each of them I would like to use Vue. And here I have a few questions:
1) Do I need to create separate app.js files for each page with a Vue instance in the / resources / js / folder? Something like:
app-account.js
const app-account = new Vue({
el: '#app-account ',
});
app-players.js
const app-players= new Vue({
el: '#app-players',
});
etc.?
If not - how to do it? Declare all components in one app.js file? And is this correct? Because then when you enter mypage.com/account in the app.js file in / public / js / all other Vue components are stored. So the actual component is displayed on the page and all components are downloaded on the page.
2) Why does every component have to be the default?
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
3) How to use Laravel + Vue correctly when you do not want the site to be SPA?
4) Is it correct that all data is transmitted along with the view? Is it better to create controllers only for displaying the view and download data via Vue from api?
5) What about the features from the Blade template system?
I could display a link to the route in them via {{route ('name')}}. The only way to achieve this in Vue is to pass a parameter to the component? Is this the correct way?
<example-component routeToXXX="{{route ('name')}}" />

Welcome to Vue world.
Since Laravel/PHP at navigation between pages leads browser to rerender DOM, its your choice if you separate app files or just write inline js wrapped with <script> (if you do that ensure vuejs is loaded before your script/defered). In case you want to keep Laravel your core, you may also consider diving into livewire, alternatively you have to explore what the world is trying like: VUE2 component register in Laravel
It's a Javacsript syntax, basically SFC (Single File Components) are supposed to export JS data/object/functions which can be used or loaded, Vue has a clear documentation, try it. Learning Vue, makes you learn JS (suggestion: consider learning the basics, start by understanding difference between sync, async, loops, data types, functions, function functions).
There's no concrete way that you have to follow in order to achieve what you need or accomplish certain task. In any case if your needs are met by your solution at your stage of career, that might be the correct way. Just keep trying and outcome your abilities by time (reviewing other's code/libraries helps).
This is matter of choice, SSR (ServerSideRendering) is commonly used in cases you do not want to expose the logic in the frontend or have security concerns. There are also scenarios where you perform API calls to enhance overall performance like pagination or filters. However your data publicity/privacy always depends on how you authenticate users, each API call must ask for a valid access token that will ensure the backend, that credentials are met to reach the data. With experience in frontend you'll be convinced which are the best practices.
Laravel has a blade helper to ignore templating engine (#verbatim,#endverbatim and others). Passing data to your Vue part if its inline script you may open php tags like within your #verbatim section. In other cases if you already know what you are about to pass your JS, you can define a global variable somewhere in between your blade view like <script> var globalVar = { url1: "<?= route('name'); ?>", url2: "<?= route('name2'); ?>" } </script> or you can echo out encoded json so it renders the JS variable like var globalVar = <?= json_encode($yourVariable); ?>;
Finally PHP and JS are both two different worlds, aiming towards a similar syntax. It's a big decision to consider loose coupling API and View logic, but it might pay well in long term.

Related

How to fetch data before component mount in Svelte?

Unlike onMount there is no beforeMount lifecycle event in SvelteJS. So, how do we fetch data that the page depends on before mounting? onMount fetches produces glitches. One can say that I can wrap dependent DOM inside if conditions. But I don't think it is the right solution. Very like in Sapper there is a preload function that can load page dependent data before mounting. What is the alternative to this (Sapper's preload) behavior in SvelteJS?
You'd create another component that doesn't render the Component until the data is ready.
<script>
import Post from "./Post.svelte";
const url = 'https://jsonplaceholder.typicode.com/posts/1';
const promise = fetch(url).then(response => response.json());
</script>
{#await promise then data}
<Post title={data.title} />
{/await}
REPL
Depending on the scenario you can use a router that has data loading supports, like the sveltekit router.
You can put the fetch code right under <script> tag
A <script> block contains JavaScript that runs when a component instance is created.
There is also context="module" attribute with <script> tag. It
runs once when the module first evaluates, rather than for each component instance
See the official docs
Noob here, to your sub-question: isnt svelte front end only? Meaning no SSR support and thus no option for preloading data with first user request.
Since, you dont have any server that would preload your data and give the user prepacked front-end (svelte pages) with data. Thus, you need sapper to provide a functionality where server can fetch data with first user request, populate front end and send it to user.. This way, user receives svelte pages, populated with data, upon first response from your server.
Since you use only svelte, user needs to contact your server more often.. First, it fetches the front-end, then front-end fetches data from back-end. Furthermore, it aint SEO friendly as robots dont wait for the subsequent server responses. Thus, your pages wont be analyzed properly as robots analyze 'blank'page, no data mounted yet, and move to next, before response can be processed.
Please, correct me If I am wrong ;)
I believe above answer is right:
1. create empty variable in script tag
2. add below onMount call and fetch data from serverto above declared variable
3. check if var is empty and show loading button
4. if var isnt empty, then show user content
6. profit?
P.S: Sorry for any misconceptions or bad English :)

Right way to pass and store data from Laravel to Vue

I'm not used to Vue components. My second problem is, I wanted to pass data from laravel blade, to vuejs component in the right way. Because what I did is I store it to props, then pass the props into the data property, like this:
//ticket blade
<ticket-create :menu-categories-prop="{{ json_encode($menuCategories) }}"></ticket-create>
//ticket component
export default {
props: ['menuCategoriesProp'],
created(){
this.menuCategories = this.menuCategoriesProp;
},
data() {
return {
menuCategories: [],
}
}
}
now I have menuCategoriesProp and menuCategories data, which is kinda redundant. Am I doing it wrong?
It is not a redundancy problem, it's a logic problem. You should not pass ANY variable from blade to view in my opinion. You should do something like this:
Your controller (maybe from the index method) checks if the request wants a JSON response, if not returns the view, otherwise the collection as a JSON response (go on to understand why).
When the view is loaded, VueJs loads the component and (this is how I do it) within the mounted method you make an Ajax call (maybe with axios) to your controller which will return the collection
In this way you have an asynchronous request management, that will allow you to refresh the data, and avoid to reload the page each time.
As I wrote before, I would avoid as much as possible to pass properties from blade to vue, unless they're context variables like user preferences or system settings.
Your code is ok. You can get categories over ajax. In your case, it is not recommended to use ajax.

Vue + Laravel: Still use old endpoint pagination?

I am working on a Laravel app that has used Blade files for a while. We are switching part of the app to use Vue now. One of the endpoints we had used pagination with a page parameter at the end of it.
For example: /store/api/users?page=1 and each page would show 20 users -- sort of like a lazyLoad.
Does this make sense to keep it like this for Vue? With Vue, shouldn't the endpoint just get me ALL the users and then I can do what I want with that data?
No, you should not query all the data and return to vuejs. If your data is huge then you will be in big trouble with slower performance. So, it's always a good idea to use Larave's paginations even while you are responding json instead of view.
For example when you were using blade, you were doing something like:
$users = User::where('column', $value)->paginate();
return view('user.index', compact('user'));
Right? Now you are using Vuejs and still have you covered with it's nice length aware paginator instance. So, now you can do something like:
$users = User::where('column', $value)->paginate();
return $users;
This Will return all paginations meta data like, total page, current page etc.
So that, you can manipulate those data perfectly in vuejs.

How should I update a component and non-component from an AJAX call?

Sorry if the question is confusing but I am just getting started with React. Basically, I am looking to start adding individual components to an existing website. Currently, when the page loads there are a couple of AJAX requests that update different parts of the page with jQuery.
For example, I make an AJAX request that is called every 30 seconds to get AccountInfo and when it returns a response, I update two separate parts of the page, let's call them AccountPanel and SideBar.
Question #1
If I were to create a component for the AccountPanel, should I make the AJAX request when the component mounts and continue to use jQuery to update the SideBar in there?
Question #2
Or is it better to create components for both and pass the AJAX response as props?
ReactDOM.render(<AccountPanel />, document.getElementById('accountPanel'));
ReactDOM.render(<SideBar />, document.getElementById('sideBar'));
Any help is appreciated :)
Actually, I think you need some state container. To share state(in your case AccountInfo) between all of your components.
Personally, I recommend using Redux. Because this container is completely predictable.
In result you code will looks like:
//create redux store somehow
ReactDOM.render(<AccountPanel store = {resuxStore}/>, document.getElementById('accountPanel'));
ReactDOM.render(<SideBar store = {resuxStore}/>, document.getElementById('sideBar'));

Top js library to work with data model and ajax?

we are working on new project using Reactjs. We drop all oldschool libs like jquery and keep just simple React with some polyfills and small 3rd party libs. It works like a charm, it is small and fast.
But now we want to integrate some logic around backend models. I am not sure how to handle that.
First question:
What is currently "best" or most using ajax library? I check some like fetch, superagent and I am not sure if they are verified and production ready.
Send one:
For example model represent User entity. I want to cover basic REST ajax calls and custom ones find, findAll, create, update, destroy, or custom toggleFollow. And it should know about model logic like fullName = function() {return firstName + " " + lastName}. It is not hard to write by myself, but there is so many catches to handle. And it should be flux or flux-like compatible :)
Any suggestions, what is today popular and "in"?
Thanks

Resources