Get parameter from URL in Vue JS - javascript

I am working on SPA (Vue JS) and Laravel as API. I want when users will receive email to click on button that will sent them to specific route (already implemented).
So now i am struggling how to get the user id from the Vue JS part.
https://domain.test/admin/users/dashboard/user/65/show
65 from the URL is the user ID, so any idea how to extract that ID with java script from Vue JS?
I am not using vue router, this is Laravel route and Vue JS component is rendered from blade file.
I have implemented something like this bellow, but client refused...
https://domain.test/admin/users/dashboard/user/show?userId=65

let id = window.location.href.split('/').slice(-2)[0]

Since you're already rendering the page in a Blade file, you should already have access to the user ID server side.
In that case, simply add the variable server side. For example:
<a :href="'https://domain.test/admin/users/dashboard/user/' + {{
$user->id }} + '/show'">Go to Dashboard</a>

To get parmeters from url you can use vue router for that like this:
const routes = [
// dynamic segments start with a colon
{ path: '/users/:id', component: User },
]
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
Here is the link for more examples and vue router documentation:
https://router.vuejs.org/guide/essentials/dynamic-matching.html
You can also get parameters with only vanilla JavaScripe like follow:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
//then you have to parse the url
const urlParams = new URLSearchParams(queryString);
const color = urlParams.get('color')
console.log(color);
// blue

Related

VueJS: How to use routing in an Multi Page App to send url query params?

I'm a bit new to VueJS, I am using the MPA approach in VueJS to create an App with multiple pages (using this answer) and I want to have a query parameter in the url that navigates to the signup page from the pricing page like "localhost:8080/signup?bundle=standard"
this is my pages structure:
(image)
I used vue router and router link to do this, but I don't know where to put
the router view as in the docs they only use it in a single page application.
How can I achieve this? How can I get the query params in a MPA app structure?
There are couple of ways for the redirection with parameter in vue.js you can simply make redirection from any method as follows:
setTimeout(() => {
return this.$router.push({name: 'Your_Router_Name_Hear', params: { bundle: 'standard' }})
}, 100);
Another way is redirection from your template with parameters:
<router-link:to="{ name: 'Your_Router_Name_Hear', params: { bundle: 'standard' }}" class="button" >
<i class="fa fa-edit"></i> Edit
</router-link>

Pass parameter to Express controller from button click

Preface: I am writing a Web App using Node.js, Express, and MongoDB.
When a button is clicked I am trying to pass a parameter via URL from my index.ejs to the Express controller ItemController.js in order to dynamically create a filtered set of data.
The button is defined within index.ejs as follows:
<button type="button" class="btn btn-primary" value="/items/items" onclick="loadItems(value, 'Scripting Languages')">
Scripting Languages
</button>
In my external Javascripts file which houses miscellaneous functions, loadItems executes the following:
function loadItems(page, subcategory) {
window.history.replaceState({}, '', "?subcat=" + subcategory); //set URL Param
$('#mainContent').load(page); //load item listing page into grid within HTML GridLayout
}
After this, the router/controller handles the data filtering and page rendering:
Router (item.js)
...
// Get all items
router.get('/items', item.items);
...
Controller (ItemController.js)
...
// loads item listings
itemController.items = function(req, res) {
Item.find({}).exec(function (err, items) {
if (err) {
console.log("Error:", err);
}
else {
var URLSubcat = "Scripting Languages"; //this variable needs to change
var filtered = items.filter(function(el) {
return el.subcategory === URLSubcat;
});
res.render("../views/items/items", {items: filtered});
}
});
};
...
I have tried using req.query.subcat in order to try and grab the parameter from the URL, however it comes back as undefined. I have also tried the techniques in the links below to no avail. What should I be doing to accomplish this? Is there a better way to go about this?
Previously Tried
How to get GET (query string) variables in Express.js on Node.js?
How to access the GET parameters after "?" in Express?
$('#mainContent').load(page);
The URL you are requesting is stored in the page variable.
loadItems(page, subcategory)
… which is defined as an argument
onclick="loadItems(value, 'Scripting Languages')"
… which is passed from the onclick event handler
value="/items/items"
… which gets it value from that attribute.
The query string doesn't show up because the URL you are requesting does not include a query string!
The only query string you have is from here:
window.history.replaceState({}, '', "?subcat=" + subcategory);
… which modifies the URL in the browser addressbar and history without actually requesting it.

Angular not able to get full url

requirement: need to hit the url
localhost:4200/keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
then capture:
[keyone=valueone, keytwo=value2109808329csdc0qwd, keythree=xyz#pqr.com];
When I am hitting the url using angular 5 its changing to
localhost:4200/keyone
I am not getting the full url. Its disappearing from the = .
Added a path and attached the required info as an id.
ex.
localhost:4200/item?keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
And got the url values in windows.location.url
/item?keyone=valueone&keytwo=value2109808329csdc0qwd&keythree=xyz#pqr.com
The url looks fine and you should get into a url routed page which is mapped to this irl. As I guess there are no routing available to the url you are providing, its redirecting to a one it found
Normally in angular we catch url params in below way
const routes: Routes = [{
path: ':keyone/:keytwo/:keythree',
component: SomeComponent,
resolve: {
resolvedData: SomeResolverService,
}
}
And then in your resolver or component you can get them by
// inject ActivatedRouteSnapshot
route: ActivatedRouteSnapshot
Then get the params
route.params.keyone, route.params.keytwo, route.params.keythree,

Can this jQuery dynamic DOM manipulation be done with Vuejs?

I have a page that makes AJAX requests to update content. I make the request and get JSON back that looks something like this:
{
"item": {
"id": "myElementToChange",
"value": "My Content to update"
}
}
I then parse it and update the page like this:
var str = '{"item": {"id": "myElementToChange","value": "<h1>My Content to update</h1>"}}';
var json = JSON.parse(str);
var $element = $("#"+json.item.id );
$element.html(json.item.value);
Can I do something similar in Vuejs? Or do I have to predefine a template to accommodate each type of IDs that I want to update?
http://jsfiddle.net/ogewwqzt/
I would say first that even if you use Vuejs instead of jQuery, you can still use plain js functions in your vuejs code, such as:
document.getElementById(json.item.id).innerHTML = json.item.value;
Of course it is not taking advantage of the Vuejs functionalities.
The vue way would be to use declarative rendering :
<div id="app">
{{ message1 }}
{{ message2 }}
</div>
var app = new Vue({
el: '#app',
data: {
message1: 'yo',
message2: 'yo2'
}
})
then do your ajax call in a method, update the data (message1 and message2) with the result of your call and let vuejs reactivity features update the DOM.
Also, it seems like a very weird choice to have your server directly send an HTML id. Why would the back-end need to know the name of your html id ? You probably want to be able to change an html id without modifying the server code.

How to link JS route var and Symfony 2 URLs

I would like to know what is the most flexible solution to link SF2 routes & a JS var which is containing the routes.
For static routes, I don't have any problems, but when I want to connect URL with parameters, i did not find any solution (not hard-coded).
How can I do if I edit the routing.yml file, Dynamics URL on change
I'm using var url = "domain.com/path/to/url/with/" + token + "/and/" + name for generating but it is not flexible.
I know that twig generated urls are server side etc...
Any solutions ?
Ex :
JS
var route = {
home : "{{ path("home") }}",
custom_route : "{{ path("my_custom_route") }}"
}
Routing.yml
my_custom_route:
pattern: /path/to/url/with/{token}/and/{name}
defaults: { _controller: "SupboxCloudBundle:Public:file" }
I think you could try FOSJSRoutingBundle.
Well, this sort of depends on the result you are trying to achieve. Are you doing this in some sort of JS app?
If it were me, I would render the routes, or route parameters in the DOM. I wouldn't mess with rendering anything in the JS and I would make the JS code abstract.
For instance:
<div data-custom="{{ path("my_custom_route") }}"></div>
<div data-home="{{ path('home') }}"
or
whatever
then you can grab your routes in JS when needed (from the first example):
var route = {
home: $('div[data-home]').data('home'),
custom_route: $('div[data-custom]').data('custom')
}
This is a little messy as I'm just trying to show you a concept. However your actual implementation would depend on the actual result you are trying to achieve.
If you comment a more specific intent below I will provide a better solution for you.

Categories

Resources