Can't display data in a component - vue.js

I have request that returns json data...and i'm trying to display that data in vue component,but it doesn't work. In console.log is everything ok..json is something like:
[{"id":1,"body":"Hello, this is my first notification","..bla bla
here is my code
<template>
<div class="notification-container">
<p>{{ notification }}</p>
</div>
</template>
<script>
export default {
data() {
return {
notification: '',
}
},
mounted() {
axios.get('/notifications').then((response) => {
this.notification = response.data[0].body;
console.log(this.notification);
});
}
}
</script>

Try something like this :
<template>
<div class="notification-container">
<p>{{ notification /* OR this.notification[0].body */ }}</p>
</div>
</template>
<script>
export default {
data() {
return {
notification: '',
}
},
methods:{
showMsg(){
axios.get('/notifications').then( response => {
console.log(response);
this.notification = response.data[0].body;
/* OR this.notification = response; */
console.log(this.notification);
}).catch(e => {
console.log(e)
});
}
},
created() { // or mounted()
this.showMsg();
}
}
</script>

Related

Vue js: set notification count to zero

in my Vue Js code below, i created count for notification socket, so whenever a new notification received it count+ and appears beside the icon ... now i wanted to set back the count to zero when a user click on notification icon but i couldn't figure out how to do it.
below in app.vue i set a prop called number and i pass it to the sidebar to appear on all project pages , this number is the count of the notifications .. is there a way to set it back to zero after user click on the icon in the side bar?
<template>
<router-view :number="count" #send="getNewCount">
<sidebar :number="count" />
</router-view>
</template>
<script>
import sidebar from "#/views/Layout/DashboardLayout.vue";
import axios from "axios";
import {
io
} from "socket.io-client";
let socket = io("h***********/");
export default {
components: {
sidebar,
},
data() {
return {
user2: JSON.parse(sessionStorage.getItem("user")),
count: 0,
today: null,
};
},
props: {
number: {
type: Number,
default: 0,
},},
async created() {
console.log(this.count);
const response = await axios.get(
`https://l*********rs/api/${this.user2._id}/`, {
headers: {
Authorization: "Bearer " + sessionStorage.getItem("user"),
},
}
);
// await this.$store.dispatch("user", response.data.response);
socket.emit("user_connected", this.user2.username);
// console.log(this.user2,"userr")
socket.on("verify_connection", (data) => {
this.verify_connection = data;
console.log(data, "s")
});
socket.emit("user_connected", this.user2.username);
socket.on("verify_connection", (data) => {
console.log("heyy", data);
this.verify_connection = data;
});
socket.on("updated_flat", (data) => {
console.log("heyy", data);
this.makeToast(" success ", "'b-toaster-top-center");
});
socket.on("test", (data) => {
console.log("heyy", data);
// this.makeToast("success", "b-toaster-top-right");
});
;
},
methods: {
// playSound() {
// var audio = document.getElementById("audio");
// audio.play();
// },
getNewCount(data) {
this.count = data;
},
makeToast(variant = null, toaster, append = false) {
this.$bvToast.toast(" edited ", {
title: "BootstrapVue Toast",
variant: variant,
autoHideDelay: 10000,
toaster: toaster,
position: "top-right",
appendToast: append,
});
// this.playSound();
this.count = this.count + 1;
console.log(this.count,"count");
},
}
}
</script>
sidebar:
<template>
<div class="wrapper">
<side-bar >
<template slot="links">
<sidebar-item v-if="roles ==='Admin'"
:link="{
name: ' notifications',
path: '/notifications',
icon: 'ni ni-bell-55 text-green'
}">
</sidebar-item>
<p class="notifCount" v-if="roles ==='Admin'"> {{ number }} </p>
</template>
</side-bar>
<div class="main-content">
<dashboard-navbar :type="$route.meta.navbarType"></dashboard-navbar>
<div #click="$sidebar.displaySidebar(false)">
<fade-transition :duration="200" origin="center top" mode="out-in">
<!-- your content here -->
<router-view></router-view>
</fade-transition>
</div>
<content-footer v-if="!$route.meta.hideFooter"></content-footer>
</div>
</div>
</template>
<script>
/* eslint-disable no-new */
import PerfectScrollbar from 'perfect-scrollbar';
import 'perfect-scrollbar/css/perfect-scrollbar.css';
function hasElement(className) {
return document.getElementsByClassName(className).length > 0;
}
function initScrollbar(className) {
if (hasElement(className)) {
new PerfectScrollbar(`.${className}`);
} else {
// try to init it later in case this component is loaded async
setTimeout(() => {
initScrollbar(className);
}, 100);
}
}
import DashboardNavbar from './DashboardNavbar.vue';
import ContentFooter from './ContentFooter.vue';
import DashboardContent from './Content.vue';
import { FadeTransition } from 'vue2-transitions';
export default {
components: {
DashboardNavbar,
ContentFooter,
DashboardContent,
FadeTransition
},
props: {
number: {
type: Number,
default: 0,
},
},
methods: {
initScrollbar() {
let isWindows = navigator.platform.startsWith('Win');
if (isWindows) {
initScrollbar('sidenav');
}
},
},
computed: {
roles() {
let roles = JSON.parse(sessionStorage.getItem('user')).role;
return roles;
},},
mounted() {
this.initScrollbar()
}
};
</script>
Emit an event from sidebar and handle the event in the main app.
main app:
<template>
<!-- ... -->
<sidebar :number="count" #reset="onReset" />
<!-- ... -->
</template>
<script>
export default {
// ...
methods: {
onReset() {
// api calls, etc.
this.count = 0;
}
}
}
</script>
sidebar:
<template>
<!-- ... -->
<button #click="$emit('reset')">Reset notification count</button>
<!-- ... -->
</template>

Access array value in promise

I have emited value from the child and returning the value in a parent, but when I'm trying to access it prints me just blank array?
I haven't dealt with promises in the past, so I don't know much about that...I know something about async and await method..but I don't know how to bundle this function into this.
Thanks in advance for your help.
This is what I have...
insertMessage.vue
export default {
data(){
return{
message:'',
isLoading:false,
}
},
methods:{
addMessage(){
if(this.message !=''){
this.sendData();
} else{
}
},
sendData(){
this.isLoading = true;
this.$http.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms}).then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
this.$root.$emit('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
this.isLoading = false;
});
}
}
}
</script>
print.vue
<template>
<div class="msg_history">
<get_message :messages="messages"></get_message>
<add_message></add_message>
</div>
</template>
<script>
import addMessage from './add-message';
import getMessage from './get-messages';
export default {
components: {
get_message: getMessage,
add_message: addMessage,
},
data() {
return {
messages: []
}
},
mounted(){
this.$root.$on('new_message', (data) => {
this.messages.push(data);
});
},
}
</script>
fetchMessages.vue
<template>
<div class="incoming_msg">
<div class="received_msg">
<div v-for="message in messages" class="received_withd_msg">
{{message.created}} //This is what I want
{{message}} //This is working but print just { "promise": {} }
</div>
</div>
</div>
</template>
<script>
export default {
props:['messages'],
data(){
return{
}
}
}
</script>
You can just do emit in then:
this.$http.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms}).then((response) => {
if(response.body != 'Error'){
response.json().then( json => {
this.message = '';
console.log(json);
this.$root.$emit('new_message', json);
});
} else {
this.isLoading = false;
}
}, (response) => {
this.isLoading = false;
});

Vue.js return data from axios

<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ getUser(comment.student_idx) }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: {}
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies
}
})
},
methods: {
getUser (idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
return response.data.data.member.name
}
})
}
}
}
</script>
I would like to load the comments at created and print them out using v-for.
In v-for, I would like to load the member.name from each comment
But {{ getUser(comment.student_idx) }} is undefined.
I don't know how to return data from axios
Help me please!!
Your method should not be async for stable run code. My recomendation is next code:
<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ comments['user'] }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: []
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies;
if(this.comments)
for(let comment of this.comments){
this.getUser(comment, comment.student_idx);
}
}
})
},
methods: {
getUser (comment, idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
this.$set(comment, 'user', response.data.data.member.name);
}
})
}
}
}
</script>

Access the variables of a component

I'd like to access a component variable. This variable is modified by an html input.
Here is my current code
Parent :
<template>
<component>Child</component>
</template>
<script>
export default {
data () {
return {
dataChild : '',
}
</script>
Child :
<template>
<input type="text" name="data" v-model="data" class="form-control">
</template>
<script>
export default {
data () {
return {
data: ''
}
}
}
</script>
I've looked all over the internet but nothing works on my side or I'm doing wrong :(
Thanks in advance
you can use like below:
Parent
<template>
<component #input-child="childData"></component>
</template>
<script>
import Component from "#/components/Component";
export default {
components: { Component },
data() {
return {
dataChild: ""
};
},
methods: {
childData(data) {
console.log(data);
// you can assign it to dataChild variable
}
}
};
</script>
Child
<template>
<input
type="text"
name="data"
v-model="data"
#input="$emit('input-child', data)"
class="form-control"
/>
</template>
<script>
export default {
data() {
return {
data: ""
};
}
};
</script>
The standard way to send data from child component to parent in vue is to emit that inside child and listen for event inside parent. Like this:
Child:
export default {
data: () => ({ dataChild: 'TEST' }),
methods: {
send () {
this.$emit('data', this.dataChild)
}
},
mounted () { this.send() }
}
Parent:
<div>
<child #data="get"></child>
</div>
export default {
data: () => ({ data: '' }),
methods: {
get(value) {
this.data = value
}
}
}

Call $emit after dispatch action in Vuejs

I have a parent component:
<template>
<div class="w-full">
<div class="card-body">
<city-edit-form :form="form" :resource="resource" #save_resource="func">
</city-edit-form>
</div>
</div>
</template>
<script>
export default {
methods: {
func() {
console.log("test");
}
}
};
</script>
And child component:
<template>
<div>
<form action="#" method="POST" #submit.prevent="submit" v-else>
<button type="submit" class="btn-green">Save</button>
</form>
</div>
</template>
<script>
import { UPDATE_RESOURCE } from "../../../Stores/action-types";
export default {
props: {
form: { required: true },
resource: { required: true }
},
methods: {
submit() {
this.$store
.dispatch(`city/${UPDATE_RESOURCE}`, this.form)
.then(() => this.$emit("save_resource"));
}
}
};
</script>
And action is:
[UPDATE_RESOURCE]({ commit, state }, form) {
commit(SET_LOADING, true);
return ResourceService.update(state.resource.id, form)
.then(({ data }) => {
commit(SET_RESOURCE, data);
})
.catch(errors => {
commit(SET_ERRORS, errors.response.data);
})
.finally(() => commit(SET_LOADING, false));
});
},
When I submit form, action has been dispatched, but nothing emitted.
Nothing logged in console. Where I make mistake?
update
When I check Vue toolbar's Event tab, I see this:
I think event has been emmitted, but console.log logs nothing in console! So wired!
Use return keyword while resolve or reject is triggered
[UPDATE_RESOURCE]({ commit, state }, form) {
commit(SET_LOADING, true);
return new Promise((resolve, reject) => {
ResourceService.update(state.resource.id, form)
.then(({ data }) => {
commit(SET_RESOURCE, data);
return resolve();
})
.catch(errors => {
commit(SET_ERRORS, errors.response.data);
return reject();
})
.finally(() => commit(SET_LOADING, false));
});
},
instead of emitting events (nothing wrong with that) you could use mapGetters
<template>
<div class="w-full">
<div class="card-body">
<city-edit-form :form="form" :resource="myResource">
</city-edit-form>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
myResource: 'Stores/action-types/SET_RESOURCE', <---- needs to be modified
}),
}
};
</script>
this is assuming you have made any getters