v-on:click event Vue.js to show user posts - javascript

I'm a student and I'm just getting into Vue.js so I'm still very new to it. Right now I'm making a project where I'm getting usernames from an API and when you click on the user it has to show the related post, but this is not working. When I click the button with the v-on:click event. nothing happens, not even in the console. So I hope someone can help me with my problem, I would really appreciate it.
main.js :
const app = new Vue({
el: "#app",
data: {
users: [],
posts: [],
},
methods: {
Showpost(id, i) {
fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
.then(response =>response.json())
.then((data) => {
this.posts = data;
})
},
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then((data) => {
this.users = data;
})
},
template: `
<div>
<td v-for="user, i in users">
<button v-on:click="Showpost(user.id, i)" >{{ user.name }}</button>
</td>
<h1>{{ posts.title }}</h1>
</div>
`,
});
html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<div id="app">
</div>
<script src="https://unpkg.com/vue"></script>
<script src="./main.js"></script>
</body>
</html>
json users :
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
json posts :
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Try to create a property called post and update it on every click on a specified user by assigning this.post=data[i]:
new Vue({
el: "#app",
data: {
users: [],
posts: [],
post: ''
},
methods: {
Showpost(id, i) {
fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
.then(response => response.json())
.then((data) => {
this.post = data[i];
})
},
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then((data) => {
this.users = data;
})
},
template: `
<div class="flex">
<div v-for="user, i in users">
<button class="btn" v-on:click="Showpost(user.id, i)" >{{ user.name }}</button>
</div>
<h1>{{ post.title }}</h1>
</div>
`,
});
.flex{
display:flex;
flex-wrap:wrap;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Vue.delete">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>
<body>
<div id="app">
</div>

Related

I can't select a row from a DataTable

I have a DataTable that is created dynamically according to the result of a SELECT, the first time it is created it does not give me any problem, but when I change the SELECT, still reloading the table, the data of it cannot be accessed
In the browser console appears this error message:
Uncaught TypeError: can't access property "name", informe is undefined
file:///C:/Users/jordi.burgos/Downloads/ejemplo minimo/index.js:40
jQuery 8
file:///C:/Users/jordi.burgos/Downloads/ejemplo minimo/index.js:36
jQuery 2
You can see this error in https://codepen.io/jordibonarea/pen/OJvNOZB
I have created a minimum code to be able to model the example:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ejemplo mínimo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- DataTables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script src="index.js"></script>
</head>
<body>
<h1>Este es el ejemplo mínimo para que de error el DataTable</h1>
<select name="prueba_select" id="prueba_select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<table id="table_prueba"></table>
<div id="item_selected"> </div>
</body>
</html>
index.js
$(document).ready(function () {
$('#prueba_select').change(function (e) {
e.preventDefault();
var $tabla_modal_informes = $('#table_prueba').DataTable({
destroy: true,
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": 5421
},
{
"name": "Garrett Winters",
"position": "Director",
"salary": "5300",
"start_date": "2011/07/25",
"office": "Edinburgh",
"extn": "8422"
},
// ...
],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
});
//cuando hacemos click en sus filas
$('#table_prueba').on('click','tr',function () {
//$tabla_modal_informes.rows().deselect();
// Ontiene datos de la fila seleccionada
let informe = $tabla_modal_informes.row(this).data();
$('#item_selected').html('<h3>' + informe.name +'</h3>');
});
});
});
Thanks
I just changed the scope where $table_modal_informes is defined putting its declaration outside of the ready event handler so that you'll have only one reference to one DataTable object at any given time.
As you can see in the snippet, now you are free to select rows from the table any time also after the selected data table was changed from the corresponding dropdown:
var $tabla_modal_informes;
$(document).ready(function () {
$('#prueba_select').change(function (e) {
e.preventDefault();
$tabla_modal_informes = $('#table_prueba').DataTable({
destroy: true,
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": 5421
},
{
"name": "Garrett Winters",
"position": "Director",
"salary": "5300",
"start_date": "2011/07/25",
"office": "Edinburgh",
"extn": "8422"
},
// ...
],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
});
//cuando hacemos click en sus filas
$('#table_prueba').on('click','tr',function (event) {
//$tabla_modal_informes.rows().deselect();
// Ontiene datos de la fila seleccionada
let informe = $tabla_modal_informes.row(this).data();
$('#item_selected').html('<h3>' + informe.name +'</h3>');
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ejemplo mínimo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- DataTables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
</head>
<body>
<h1>Este es el ejemplo mínimo para que de error el DataTable</h1>
<select name="prueba_select" id="prueba_select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<table id="table_prueba"></table>
<div id="item_selected"> </div>
</body>
</html>

Cannot get the data from axios with api - vue js

I have an issue when i get the data with vue js, it returns a HTML not json. I conse the route params it show an id of the post. This is my code in vue:
axios.get("api/posts/" + this.$route.params.id).then(response => {
console.log(this.$route.params.id);
console.log(response.data);
});
And this is the response data :
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
<script src="http://127.0.0.1:8000/js/app.js" defer></script>
</head>
<body>
<div id="app">
<index></index>
</div>
</body>
</html>
But in the postman, i access the url "api/posts/1" it show json data
{"id": 1,"title": "Schambergerstad Fancy Rooms",
"description": "Qui minima tempora ea modi maiores. Quaerat non aut porro vel occaecati. Deleniti quaerat quod veniam. Dolor ducimus facilis molestiae omnis fuga occaecati.",
"created_at": "2020-06-04T11:28:25.000000Z","updated_at": "2020-06-04T11:28:25.000000Z"
}
But i see in network tab, the request url is "http://127.0.0.1:8000/posts/api/posts/1". Why become to that url? I call it in axios is "api/posts/1"
How to fix it?
try adding headers Content-Type json
axios.get("/api/posts/" + this.$route.params.id, {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log(this.$route.params.id);
console.log(response.data);
});
Okay sorry it's just typo axios.get("api/posts/" + this.$route.params.id) it's should add "/" before "api/posts/"
axios.get("/api/posts/" + this.$route.params.id)

Fetch-api OpenWeather, problem to acess attribute 'name' value and display it

My question is, I can display both 'description' and 'temp', so, why can't I retrieve the 'name' of the city. Please look at a fetch response:
var button = document.querySelector('.button')
var inputValue = document.querySelector('.inputValue')
var name = document.querySelector('.name');
var desc = document.querySelector('.desc');
var temp = document.querySelector('.temp');
//trigering Action Fetch api
button.addEventListener('click',function(){
fetch ('https://api.openweathermap.org/data/2.5/weather?q='+inputValue.value+'&appid=0f91ec65ce9099b9b43a35a9f89f6f26')
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
name.innerHTML = nameValue;
temp.innerHTML = tempValue;
desc.innerHTML = descValue;
})
.catch(err => alert("Wrong city name!"))
})
{
"coord": {
"lon": 145.77,
"lat": -16.92
},
"weather": [{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03n"
}],
"base": "stations",
"main": {
"temp": 300.15,
"pressure": 1007,
"humidity": 74,
"temp_min": 300.15,
"temp_max": 300.15
},
"visibility": 10000,
"wind": {
"speed": 3.6,
"deg": 160
},
"clouds": {
"all": 40
},
"dt": 1485790200,
"sys": {
"type": 1,
"id": 8166,
"message": 0.2064,
"country": "AU",
"sunrise": 1485720272,
"sunset": 1485766550
},
"id": 2172797,
"name": "Cairns",
"cod": 200
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css"/>
<title>Request APP template</title>
</head>
<h1>Simple weather App</h1>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button"></div>
</div>
<div>
<h1>
Current city weather conditions:
</h1>
</div>
<div class="display">
<h1 class="name"></h1>
<p class="desc"></p>
<p class="temp"></p>
<i class="icon"></p>
</div>
<script src="app.js"></script>
</body>
</html>
Am I wrong at var nameValue = data['name']? am I missing something?
thanks in advance
I am looking forward to learning how to use fetch correctly to improve my projects.

View output doesn't show up

I'm working on the tutorial to display contact details on my page. The code doesn't display the first and last name. Please find the code below.
My index.html
<!DOCTYPE html>
<html data-ng-app="myContactApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="app.js"></script>
<title>My Contact Application</title>
</head>
<body>
<h1>Contact App</h1>
<div data-ng-controller="contactController as ctrl">
<div data-ng-repeat="con in ctrl.contactArr">
<span>{{con.name.first+ " "+con.name.last}}</span>
</div>
</div>
</body>
</html>
My app.js file
var app=angular.module("myContactApp",[]);
app.controller("contactController",contactCtrl);
function contactCtrl(){
this.contactArr = [
{
"gender": "male",
"name": {
"title": "mr",
"first": "romain",
"last": "hoogmoed"
},
"location": {
"street": "1861 jan pieterszoon coenstraat",
"city": "maasdriel",
"state": "zeeland",
"postcode": 69217
},
"email": "romain.hoogmoed#example.com",
"login": {
"username": "lazyduck408",
"password": "jokers",
"salt": "UGtRFz4N",
"md5": "6d83a8c084731ee73eb5f9398b923183",
"sha1": "cb21097d8c430f2716538e365447910d90476f6e",
"sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
},
"dob": "1983-07-14 07:29:45",
"registered": "2010-09-24 02:10:42",
"phone": "(656)-976-4980",
"cell": "(065)-247-9303",
"id": {
"name": "BSN",
"value": "04242023"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/83.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
"nat": "NL"
}
]
}
My page is not showing the first and last name when I run through HTTP-server. Am I doing anything wrong?
Your code works fine. Kindly see whether app.js or angular dependency properly loaded or not.
https://jsfiddle.net/Prasanna15/m3q70umq/
you can check your code.
try to use https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js this one
Your code runs like a charm. There is no mistake in it. Please ensure that all ressources (app.js & https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js) are loaded. Open up the network tab in your browser debugger to check this. Also ensure you cleaned up your browser cache.
<!DOCTYPE html>
<html data-ng-app="myContactApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="app.js"></script>
<title>My Contact Application</title>
</head>
<body>
<h1>Contact App</h1>
<div data-ng-controller="contactController as ctrl">
<div data-ng-repeat="con in ctrl.contactArr">
<span>{{con.name.first+ " "+con.name.last}}</span>
</div>
</div>
</body>
</html>
--> demo fiddle

Using Angular and Youtube API to display playlists and video details

I am new to Angular but I thought I would get my feet wet with it by using the Youtube API v3. I am struggling getting the playlists from a channel to display in a dropdown on the html page. Also, when a playlist is selected from the dropdown I want to display the title and thumbnail of every video in the selected playlist. I am new to this so I would really appreciate some help.
Here is what I have:
<html lang="en">
<head>
<title>Angular Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-1.11.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script>
var app = angular.module('ph', []);
var key = '';
app.factory('youtubeService', ['$http', function ($http) {
function getPlaylists(channelId) {
return $.get("https://www.googleapis.com/youtube/v3/channels", { params: {part: 'snippet', channelId: channelId, key: key} });
}
function getPlaylistVideos(id) {
return $http.get('https://www.googleapis.com/youtube/v3/videos', { params: { part: 'snippet', id: id, key: key } });
}
return { getPlaylists: getPlaylists, getPlaylistVideos: getPlaylistVideos }
}]);
app.controller('ctrl', ['$http', '$scope', 'youtubeService', function ($http, $scope, youtubeService) {
youtubeService.getPlaylists('UC1P0NQW6aixa5SUTbPF5CjQ').then(function (response) {
$scope.playlists = response.data.items;
});
$scope.getPlaylistVideos = function (selection) {
youtubeService.getPlaylistVideos(selection.snippets.id).then(function (response) {
$scope.playlistvideos = response.data.items;
});
}
}]);
</script>
</head>
<body ng-app="ph">
<div class="row">
<!-- BEGIN Playlist Section -->
<section id="playlistsection">
<div class="col-lg-12">
<div class="col-lg-6">
<table id="playlistvideostable" class="table table-responsive table-striped">
<thead>
<tr>
<th>Name</th>
<th>Thumbnail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="video in playlistvideos">
<td>
{{video.snippet.title}}
</td>
<!--<td>
<img src="{{video.snippet.thumbnails.default.url}}" alt="Video Image"/>
</td>-->
</tr>
</tbody>
</table>
</div>
<div class="col-lg-6">
<h3>Available</h3>
<hr>
<select id="playlists"
ng-options="playlist.snippet.title for playlist in playlists track by playlist.snippet.id"
ng-model="data.selectedOption"
ng-change="getPlaylistVideos(data.selectedOption)"
class="form-control">
</select>
</div>
</div>
</section>
<!-- END Playlist Section -->
</div>
</body>
</html>
Here is an example of what getPlaylists brings back in JSON:
{
"kind": "youtube#channelListResponse",
"etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/mtu1ek5RgV1XsIgIoPS7GNv8NkI\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/TEgtFpLB_KhJ-XEwy-yOJneYIYw\"",
"id": "UC1P0NQW6aixa5SUTbPF5CjQ",
"snippet": {
"title": "Aaron Johnson",
"description": "",
"publishedAt": "2014-07-11T15:19:25.000Z",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/-py7sd_PnqBI/AAAAAAAAAAI/AAAAAAAAAAA/Q6pYI0EC7No/s88-c-k-no/photo.jpg"
},
"medium": {
"url": "https://yt3.ggpht.com/-py7sd_PnqBI/AAAAAAAAAAI/AAAAAAAAAAA/Q6pYI0EC7No/s240-c-k-no/photo.jpg"
},
"high": {
"url": "https://yt3.ggpht.com/-py7sd_PnqBI/AAAAAAAAAAI/AAAAAAAAAAA/Q6pYI0EC7No/s240-c-k-no/photo.jpg"
}
},
"localized": {
"title": "Aaron Johnson",
"description": ""
}
}
}
]
}
You have several issues with your code:
You do not have a controller defined in your code, without it, your scope will not update.
The API call is lacking a filter, such as categoryid.
You are using $ to get the playlists, which is a Jquery request. Use $http
Because of the above, you are coming outside of angular which then causes it to lose track of scope updates. Wrapping the assignment with $scope.$apply, will fix this. However, using $http will make this not necessary.
Please see below an updated version of your code which works. I have not continued on to the Video Playlist side of things, which you can do for practice.
<html lang="en">
<head>
<title>Angular Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-1.11.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script>
var app = angular.module('ph', []);
var key = 'AIzaSyAYPrc9K2Fa2GopcBMuFNRxpAQrVJJvzC0';
app.factory('youtubeService', ['$http', function ($http) {
function getPlaylists(channelId) {
return $.get("https://www.googleapis.com/youtube/v3/channels", { part: 'snippet', channelId: channelId, key: key, categoryId: "GCQmVzdCBvZiBZb3VUdWJl" });
}
function getPlaylistVideos(id) {
return $http.get('https://www.googleapis.com/youtube/v3/videos', { params: { part: 'snippet', id: id, key: key } });
}
return { getPlaylists: getPlaylists, getPlaylistVideos: getPlaylistVideos }
}]);
app.controller('ctrl', ['$http', '$scope', 'youtubeService', function ($http, $scope, youtubeService) {
youtubeService.getPlaylists('UC1P0NQW6aixa5SUTbPF5CjQ').then(function (response) {
$scope.$apply(function () {
$scope.playlists = response.items;
})
});
$scope.getPlaylistVideos = function (selection) {
youtubeService.getPlaylistVideos(selection.snippets.id).then(function (response) {
$scope.playlistvideos = response.data.items;
});
}
}]);
</script>
</head>
<body ng-app="ph">
<div class="row">
<!-- BEGIN Playlist Section -->
<section id="playlistsection">
<div class="col-lg-12" ng-controller="ctrl">
<div class="col-lg-6">
<table id="playlistvideostable" class="table table-responsive table-striped">
<thead>
<tr>
<th>Name</th>
<th>Thumbnail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="video in playlistvideos">
<td>
{{video.snippet.title}}
</td>
<!--<td>
<img src="{{video.snippet.thumbnails.default.url}}" alt="Video Image"/>
</td>-->
</tr>
</tbody>
</table>
</div>
<div class="col-lg-6">
<h3>Available</h3>
<hr>
<select id="playlists"
ng-options="playlist.snippet.title for playlist in playlists track by playlist.snippet.id"
ng-model="data.selectedOption"
ng-change="getPlaylistVideos(data.selectedOption)"
class="form-control"></select>
</div>
</div>
</section>
<!-- END Playlist Section -->
</div>
</body>
</html>
The changes being: Add a ng-controller attribute
<div class="col-lg-12" ng-controller="ctrl">
Send in a filter. This should also use $http not $.get - Also note the removal of the params wrapper.
function getPlaylists(channelId) {
return $.get("https://www.googleapis.com/youtube/v3/channels", { part: 'snippet', channelId: channelId, key: key, categoryId: "GCQmVzdCBvZiBZb3VUdWJl" });
}
Wrap apply because you step outside of angular
$scope.$apply(function () {
$scope.playlists = response.items;
})

Categories

Resources