<template>
<div class="ls-repo">
<div
class="row justify-content-between ls-pin-repo"
v-for="repo in repos"
:key="repo.id"
>
<div class="col-md-6">
<router-link :to="repo.html_url"
><h6>{{ repo.name }}</h6></router-link
>
<div class="row ls-r">
<div class="col mt-4">
<span>{{ repo.language }}</span>
</div>
</div>
</div>
<div class="col-md-6">
{{ repo.full_name }} <br />
{{ repo.visibility }}
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Repositories",
data() {
return {
repos: null,
search: "",
};
},
methods: {
setData(data) {
this.repos = data;
console.log(this.repos.node_id);
},
searchData() {
axios
.get("https://api.github.com/repos/dimaswntech/" + this.search, {
headers: {
Authorization: "token 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",
},
})
.then((response) => {
this.setData(response.data);
console.log(response.data);
})
.catch((error) => console.log(error));
console.log(this.search);
},
},
mounted() {
axios
.get("https://api.github.com/users/dimaswntech/repos", {
headers: {
Authorization: "token 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",
},
})
.then((response) => {
this.setData(response.data);
console.log(this.repos);
})
.catch((error) => console.log(error));
},
};
</script>
<style></style>
Im sorry friends, let me ask something. I am use vue js and i will fetch data from api github. In my method with name "seachData()" and Mounted part, i use axios. But i don't know, i got an error if i fill the input tag like this
<input
class="form-control input-repo"
type="text"
v-model="search"
v-on:keyup.enter="searchData"
/>
And my error said. my code has variable with null value. i those code i did not fill the input tag. So i hope you guys can help me.
Related
I am currently working on a VueJs3 Project. I already coded a login system, which works perfectly fine. I now want to have a div on the homepage, that tells the user with which account they are logged in.
"You are logged in as:" + username
I therefore, have to send the username from the login component to the home component. Can someone help me out here? I have tried out a lot of ways but none of them seem to work.
Btw. the components are all saved in the components folder
Here is my code:
home.vue
<div class="home">
<h1>You are logged in as: {{currentusername}}</h1>
<Maschinen/>
</div>
</template>
<script>
import Maschinen from '#/components/Maschinen.vue'
import axios from 'axios'
export default {
name: 'Home',
components: {
Maschinen
},
data() {
return {
currentusername: null,
}
},
async created() {
const response = await axios.get('http://localhost:8080/user/hetwinuser', {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
});
this.currentusername= (response.data.username);
}
}
</script>
login.vue:
<template>
<form #submit.prevent="handleSubmit">
<h1>Login</h1>
<!--username + pw input for login-->
<div class="form-group">
<label id="username">Username:</label>
<input id="usernameinput" type="text" class="form-control" v-model="username" placeholder="Username">
</div>
<div>
<label id="password">Password:</label>
<input id="passwordinput" type="password" class="form-control" v-model="password" placeholder="Password">
</div>
<!--enter buttons-->
<button class="enter">Enter</button>
<router-link to="/register" id="goToRegister" tag="button">Register</router-link>
</form>
</template>
<script>
import axios from 'axios';
export default {
name: "Login",
data: () => {
return {
username: '',
password: ''
}
},
methods: {
async handleSubmit() {//executed when enter button is pressed
const data = {
username: this.username,
password: this.password
};
axios.post('http://localhost:8080/authenticate', data) //post the username + pw and will receive the token in exchange
.then(
res => {
localStorage.setItem('token', res.data.jwt);
localStorage.setItem('currentusername', this.username);
//console.log(localStorage.getItem('token'));
}
).catch(
err => {
console.log(err)
}
);
}
},
}
</script>```
username and password
Define it under store -> state.js. Then where you want it
Use it as "this.$store.state.username"
I am attempting to load calendar events from an API and then display them using Axios and Vue.js. It is working, but I am getting the following error in the console:
[Vue warn]: Error in render: "TypeError: Cannot read property
'forEach' of undefined"
My vue file is below. The content renders fine but every time the site loads the above warning shows up. Must be something simple I am missing.
<template>
<div class="row row-equal">
<div class="flex xs12">
<va-card
no-padding-h
style="overflow-x: auto;"
:title=title>
<va-timeline style="min-width: 400px;" v-if="meetings">
<va-timeline-item v-for="event in meetings">
<template slot="before">
<div
class="title text--center"
:style="{color: $themes.success}">
{{ event.start }} - {{ event.end }}
</div>
<div class="va-timeline-item__description">
{{ event.summary }}
</div>
<div class="va-timeline-item__description">
{{ event.creator }}
</div>
</template>
</va-timeline-item>
</va-timeline>
</va-card>
</div>
</div>
</template>
<script>
var moment = require('moment')
export default {
name: 'dashboard-calendars',
props: ['title'],
data () {
return {
meetings: [],
}
},
methods: {
loadCalendars () {
this.$http.get('calendar?name=' + this.$props.title + '&format=json')
.then(response => {
this.meetings = response.data
})
.catch(error => {
// handle error
console.log(error)
})
},
},
mounted () {
this.loadCalendars()
},
}
</script>
<style scoped>
.title {
font-size: 1.0em;
}
</style>
<style>
.va-card__header-title{
font-size: 1.0em !important;
}
</style>
The v-for was still being executed as the v-if='meetings' was allowing the loop to continue so using #pascalLamers response I added the length check and that worked.
<va-timeline-item v-for="event in meetings">
<template slot="before">
<div
class="title text--center"
:style="{color: $themes.success}">
{{ event.start }} - {{ event.end }}
</div>
<div class="va-timeline-item__description">
{{ event.summary }}
</div>
<div class="va-timeline-item__description">
{{ event.creator }}
</div>
</template>
</va-timeline-item>
</va-timeline>```
I would try it this way, put it in the created lifecycle hook and make it async:
var moment = require('moment')
export default {
name: 'dashboard-calendars',
props: ['title'],
data () {
return {
meetings: [],
}
},
async created() {
await this.$http.get('calendar?name=' + this.$props.title + '&format=json')
.then(response => {
this.meetings = response.data
})
.catch(error => {
// handle error
console.log(error)
})
},
}
I'm developing vlog service with flask, vue.
Between two components of vue - PostList and PostDetail vue -, I use Eventbus to send postId. PostList send postId and PostDetail receive it. And then i request GET method to server using axios and postId. And i changed data like 'this.sth = result.data' but it doesn't changed
here is my code except css
postlist
<template>
<div class="list-container">
<div class="post-list" v-for="post in posts" v-bind:key="post.key" >
<img :src="`http://54.180.79.49/${post.image}`" class="post-img">
<div class="post-container" >
<div class="post-title" v-on:click="redirect(post.post_id)"><p class="text-title">{{ post.title }}</p></div>
<div class="content-container">
<p class="post-content">{{ post.content }}</p>
<div class="meta-container">
<p class="post-meta">{{ formatDate(post.creation_time) }}, {{ post.commentCount }}개</p>
<div class="heart-container">
<img src="../assets/heart.png" class="heart-img">
<p class="heart-cnt">0</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import moment from 'moment'
export default {
name: 'PostList',
data () {
return {
posts: [],
category: '',
isAll: false
}
},
created: function () {
this.$EventBus.$on('category', (category) => {
this.isAll = !this.isAll
this.category = category
if (this.isAll === false) {
this.$http.get('/post', {params: {category: 'All'}}).then((result) => {
this.posts = result.data
console.log(result.data)
}).catch(function (error) {
console.log(error)
})
} else {
console.log(this.category)
this.$http.get('/post', {params: {category: this.category}}).then((result) => {
this.posts = result.data
console.log(result.data)
}).catch(function (error) {
console.log(error)
})
}
})
this.$http.get('/post', {params: {category: 'All'}}).then((result) => {
this.posts = result.data
console.log(result.data)
}).catch(function (error) {
console.log(error)
})
},
methods: {
tmp: function () {
console.log(1)
},
formatDate: function (date) {
return moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD')
},
redirect: function (id) {
this.$router.push('/detail')
this.$EventBus.$emit('post_id', id)
}
}
}
</script>
postdetail
<template>
<div class="body-wrapper">
<div class="profile-container">
<div class="profile-wrapper">
<img src="../assets/profile.png" class="small-profile">
<div class="intro-wrapper">
<p class="small-name">test</p>
<p class="small-intro">test</p>
</div>
</div>
</div>
<div class="all-wrapper">
<div class="title-container">
<div class="title-wrapper">
<div class="heart-wrapper">
<img src="../assets/heart.png" class="big-heart">
<div class="count">256</div>
</div>
<div class="title"><p>{{ this.info.title }}</p></div>
</div>
</div>
<div class="wrapper-wrapper">
<div class="meta-wrapper">
<div class="date"><p>{{ this.info.creation_time }}</p></div>
<div class="category"><p>{{ this.info.category }}</p></div>
</div>
</div>
<div class="detail-wrapper">
<div class="detail-body">
<!-- <img v-for="image in this.images" v-bind:key="image.key" :src="`http://54.180.79.49/${image}`" class="post-img"> -->
<div class="post-content"><p>{{ this.info.content }}</p></div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'PostDetailBody',
data () {
return {
info: {}
}
},
created: function () {
console.log(this.id)
this.$EventBus.$on('post_id', (id) => {
this.$http.get('/post/' + id).then((result) => {
this.info = result.data
}).catch(function (error) {
console.log(error)
})
})
}
}
I saw the problem in here:
redirect: function (id) {
this.$router.push('/detail')
this.$EventBus.$emit('post_id', id)
}
and
created: function () {
console.log(this.id)
this.$EventBus.$on('post_id', (id) => {
this.$http.get('/post/' + id).then((result) => {
this.info = result.data
}).catch(function (error) {
console.log(error)
})
})
}
Basically, at the time you emit the event this.$EventBus.$emit('post_id', id), PostDetail component is not created yet. So it this.$EventBus.$on isn't registered.
One possible solution is embedded id in url, and read post's id from router params
redirect: function (id) {
this.$router.push('/detail/' + id)
}
Good afternoon, I have two child components Header and Pagination. In Header, I have an input search engine and two inputs (title and body) in order to be able to add a post to Pagination. I managed to transfer the search value to the Pagination component, but I don’t know how to transfer the value from two inputs (title, body). I use to transfer the event bus. Help me please pass the value of the two inputs (title, body) into the Pagination component when you click the AddPost button.
My code on GitHub
Screenshot of app
My code of component Header:
<template>
<div class="header">
<input type="text" v-model="search" class="header_input_search" placeholder="Search" #input="saveMessage" />
<img src="src/assets/milk.png">
<div class="header_div_inputs">
<input type="text" v-model="createTitle" class="created"/>
<p><input type="text" v-model="createBody" class="createBody"/></p>
</div>
<button #click="addPost()" class="addPost">AddPost</button>
</div>
</template>
<script>
import axios from 'axios';
import {eventEmitter} from './main'
export default {
name: 'Header',
data () {
return {
search: '',
createTitle: '',
createBody: '',
}
},
methods:{
saveMessage(){
eventEmitter.$emit('messageSave', this.search)
},
}
}
</script>
My code of component Pagination:
<template>
<div class = "app">
<ul>
<li v-for="(post, index) in paginatedData" class="post" :key="index">
<router-link :to="{ name: 'detail', params: {id: post.id, title: post.title, body: post.body} }">
<img src="src/assets/nature.jpg">
<p class="boldText"> {{ post.title }}</p>
</router-link>
<p> {{ post.body }}</p>
</li>
</ul>
<div class="allpagination">
<button type="button" #click="page -=1" v-if="page > 0" class="prev"><<</button>
<div class="pagin">
<button class="item"
v-for="n in evenPosts"
:key="n.id"
v-bind:class="{'selected': current === n.id}"
#click="page=n-1">{{ n }} </button>
</div>
<button type="button" #click="page +=1" class="next" v-if="page < evenPosts-1">>></button>
</div>
</div>
</template>
<script>
import {mapState} from 'vuex'
import {eventEmitter} from './main'
export default {
name: 'app',
data () {
return {
current: null,
page: 0,
visiblePostID: '',
pSearch: ''
}
},
mounted(){
this.$store.dispatch('loadPosts')
},
computed: {
...mapState([
'posts'
]),
evenPosts: function(posts){
return Math.ceil(this.posts.length/6);
},
paginatedData() {
const start = this.page * 6;
const end = start + 6;
return this.filteredPosts.slice(start, end);
},
filteredPosts() {
return this.posts.filter((post) => {
return post.title.match(this.pSearch);
});
},
},
created(){
eventEmitter.$on('messageSave', (string) => {
this.pSearch = string
})
}
}
</script>
You can wrap title and body in an object
addPost() {
const post = {
title: this.createTitle,
body: this.createBody
}
eventEmitter.$emit('postAdd', post)
}
and then listen as normal
created(){
eventEmitter.$on('postAdd', (post) => {
console.log(post)
// do whatever you want
})
}
I have not worked on vue js but agreed with #ittus answer. You can make an object consisting of your required data which you want to share across the component and pass it as an event data.
I Created my API with PHP and here is the link: https://monstajams.co/streaming/rest/api/album/read.php
But anytime i put it in my Vue.js (Home.vue) file using axios No data is displayed on the front-end.
Here is my code below:
<ul class="ta-track-list" v-if="faqs && faqs.length">
<li class="ta-track-card column col-2 flex-column" v-for="faq of faqs">
<div class="inner">
<div class="artwork" role="link">
<span role="link" style="background-image: url(http://localhost/mymusic/assets/images/artwork/Wizkid-Soco.jpg);">
</span>
<div class="hover flex align-center justify-center">
<button id="webutton" class="ta-secondary play" onclick='playSong()'>
<i class="material-icons">play_arrow</i>
</button>
</div>
</div>
<div class="info">
<div class="title white-primary-hover" role="lin">{{ faqs }}</div>
<div class="username light-white-hover" role="link">{{ faq.artist }}</div>
<div class="released">{{ faq.duration }}</div>
</div>
</div>
</li>
</ul>
<script>
import axios from 'axios';
export default {
name: 'home',
data: () =>({
faqs: [],
errors: []
}),
created() {
axios.get('https://monstajams.co/streaming/rest/api/album/read')
.then(response => {
this.faqs = response.data;
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
The problem is your code incorrectly assumes axios.get() resolves to the raw response, but it actually resolves to a response wrapper, where the raw response is contained in a data subproperty of the wrapper, which coincidentally has the same name as the target property within the response.
You can either change your Axios response handler to get the inner data field:
axios.get('https://monstajams.co/streaming/rest/api/album/read')
.then(response => {
// this.faqs = response.data; // response.data is the raw response, but you need the array within the response (also named "data")
this.faqs = response.data.data;
})
demo
Or leave your frontend alone, and update your PHP backend to send only the array in the response:
// FROM THIS RESPONSE:
{
data: [/* PLAYLIST DATA */]
}
// TO THIS RESPONSE:
[/* PLAYLIST DATA */]
You are not updating your data accordingly to Vue docs.
For reactive changes see this document.
In the example below i update my list before Vue is mounted so rendering can occur accordingly.
let vm = new Vue({
el: "#app",
data: {
todos: []
},
methods: {
updateList() {
axios.get('https://monstajams.co/streaming/rest/api/album/read')
.then(res => {
res.data.data.forEach(item => {
Vue.set(vm.todos, vm.todos.length, {
text: item.title,
done: true
})
})
})
}
},
beforeMount() {
this.updateList()
},
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos">
<label>
<span>
{{ todo.text }}
</span>
</label>
</li>
</ol>
</div>