Vue scroll div to top inside method - javascript

Learning Vue. Trying to get a chat window div to scroll to the top when a new chat entry is found.
My Vue component is:
const app = new Vue({
el: '#toolbar-chat',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private(chat_channel)
.listen('ChatMessageSent', (e) => {
this.messages.unshift({
message: e.data.message,
player: e.data.player.nickname
});
});
},
methods: {
fetchMessages() {
axios.get(chat_get_route)
.then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.unshift(message);
this.$nextTick(() => {
this.$refs.msgContainer.scrollTop = 0;
});
axios.post(chat_send_route, message)
.then(response => {
console.log(response.data);
});
}
}
});
My chat message Template
<template>
<div ref="msgContainer" class="toolbar-chat">
<div class="row">
<div class="col-xs-12" v-for="message in messages">
<strong class="primary-font">
{{ message.player.nickname }}:
</strong>
{{ message.message }}
</div>
</div>
</div>
</template>
<script>
export default {
props: ['messages']
};
</script>
My chat send template
<template>
<div class="input-group input-group-sm">
<input id="btn-input" type="text" class="form-control" value="" required="required" maxlength="140" placeholder="Type your message here..." v-model="newMessage" #keyup.enter="sendMessage">
<div class="input-group-btn">
<button class="btn btn-primary" type="button" id="btn-chat" #click="sendMessage">
<i class="fa fa-paper-plane"></i>
</button>
</div>
</div>
</template>
<script>
export default {
props: ['player'],
data() {
return {
newMessage: ''
}
},
methods: {
sendMessage() {
this.$emit('chatmessagesent', {
player: this.player,
message: this.newMessage
});
this.newMessage = ''
}
}
}
</script>
And in my page I include the templates
<div class="col-xs-12 col-md-4" id="toolbar-chat">
<chat-messages :messages="messages"></chat-messages>
<chat-form v-on:chatmessagesent="addMessage" :player="{{ Auth::user() }}"></chat-form>
</div>
A message adds to the list OK, but I get this error:
[Vue warn]: Error in nextTick: "TypeError: Cannot set property 'scrollTop' of undefined"
Is it the way the element is named (camelCase)? What have I missed.

Since the element you want to scroll is within a component, you should implement a method on that component that you can call.
For example, in your chat-messages component...
methods: {
scrollToTop () {
this.$el.scrollTop = 0
}
}
and in your Vue instance, add a ref for that component...
<chat-messages ref="messages"...
and in the addMessage method...
this.$refs.messages.scrollToTop()

We can use scrollIntoView() method for such purpose, e.g:
this.$refs.yourRef.$el.scrollIntoView();

Related

Vue modal with a router

I am new to Vue. I am building a simple app that will list all countries and when you click on a particular country it shows you more details about the country. Idea is to open country details in a modal.
I'm stuck with displaying that modal. The modal opens, but in the background. It also opens a detail page.
CountryDetail.vue:
<script>
import axios from 'axios';
export default {
name: 'country-detail',
props: [ 'isDarkTheme' ],
data () {
return {
pending: false,
error: null,
countryInfo: null,
alpha3Code: [],
alpha3CodetoString: [],
}
},
mounted () {
this.pending = true;
axios
.get(`https://restcountries.eu/rest/v2/name/${this.$route.params.country}?fullText=true`)
.then((response) => {
(this.countryInfo = response.data)
this.alpha3CodetoString = this.alpha3Code.join(';');
})
.catch(error => (this.error = error ))
.finally( () => { this.pending = false });
},
filters: {
formatNumbers (value) {
return `${value.toLocaleString()}`
}
}
}
</script>
<template>
<modal v-model="show">
<div class="modal-mask" :class="{ darkTheme : isDarkTheme }" name="modal">
<div class="modal-wrapper">
<div class="modal-container">
<div class="modal-header">
<slot name="header">
<h1 v-if="error !== null">Sorry, an error has occurred {{error}}</h1>
<div class="loaderFlex"><div v-if="pending" class="loader"></div></div>
</slot>
</div>
<div v-for="country in countryInfo" class="countryTile modal-body" v-bind:key="country.id">
<slot name="body">
<img v-bind:src="country.flag" alt="Country Flag" class="flag">
<div class="country-details">
<h1>{{country.name}}</h1>
<div class="listDiv">
<ul>
<li><span>Population:</span> {{country.population | formatNumbers }}</li>
<li><span>Capital:</span> {{country.capital}}</li>
<li><span>Iso:</span> {{country.alpha3Code}}</li>
</ul>
<ul>
<li><span>Currencies:</span> {{country.currencies['0'].name}}</li>
<li><span>Languages:</span>
<span
v-for="(language, index) in country.languages"
v-bind:key="index"
class="languages">
{{language.name}}<span v-if="index + 1 < country.languages.length">, </span>
</span>
</li>
</ul>
</div>
</div>
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
<a #click="$router.go(-1)" class="backBtn"><i class="fas fa-arrow-left" />Go Back</a>
</slot>
</div>
</div>
</div>
</div>
</modal>
</template>
Home.vue:
<script>
import axios from 'axios';
export default {
name: 'home',
props: [ 'isDarkTheme' ],
data () {
return {
pending: false,
error: null,
countryInfo: null,
search: '',
darkMode: false,
}
},
mounted () {
this.pending = true;
axios
.get('https://restcountries.eu/rest/v2/all')
.then(response => (this.countryInfo = response.data))
.catch(error => (this.error = error ))
.finally( () => { this.pending = false });
},
filters: {
formatNumbers (value) {
return `${value.toLocaleString()}`
}
},
computed: {
filteredCountries: function () {
return this.countryInfo.filter((country) => {
if (this.region === '' ) {
return country.name.toLowerCase().match(this.search.toLowerCase());
} else if (this.search !== '') {
return country.name.toLowerCase().match(this.search.toLowerCase());
} else {
return ('blbla');
}
})
}
},
}
</script>
<template>
<div class="home" :class="{ darkTheme : isDarkTheme }">
<div class="searchBar">
<div class="searchContainer">
<i class="fas fa-search searchIcon"></i>
<input
class="searchInput"
type="text"
v-model="search"
aria-label="Search for a country..."
placeholder="Search for a country..."
/>
<ul class="searchResults"></ul>
</div>
</div>
<h1 v-if="error !== null">Sorry, an error has occurred {{error}}</h1>
<div class="loaderFlex"><div v-if="pending" class="loader"></div></div>
<div v-if="countryInfo" class="tileGrid" #click="showModal = true">
<div v-for="country in filteredCountries" class="countryTile" v-bind:key="country.id">
<router-link
:to="{ name: 'country-detail', params: {country: country.name }}"
class="linkTile"
>
<img v-bind:src="country.flag" alt="Country Flag" class="flag">
<div class="text">
<h1>{{ country.name }}</h1>
</div>
</router-link>
</div>
</div>
</div>
</template>
The router-link will always redirect you to another page, because its basically <a href="..."> see here. You don't need router if you just want to show the detail on a modal, you could just add the modal component inside the Home.vue component, then bind the modal and the countryName with props, then pass them in when clicking a button.
Home.vue:
<template>
<div>
<button #click="showDetail">
Show Detail
</button>
<CountryDetail :countryName="countryName" :showModal="showModal"/>
<div>
</template>
<script>
import CountryDetail from './CountryDetail.vue'
export default {
name: 'Home',
components: { CountryDetail },
data: () => ({
countryName: '',
showModal: false,
}),
methods: {
showDetail() {
this.showModal = true;
},
},
}
</script>
And instead of making request on mounted, you could use watch to do something like watching for the showModal prop, and make request everytime it has a truthy value. Like this:
CountryDetail.vue:
<template>
<modal v-model="showModal">
<!-- modal content -->
</modal>
</template>
<script>
export default {
name: 'CountryDetail',
props: ['countryName', 'showModal'],
watch: {
'showModal': {
deep: true,
handler(val) {
if (val && this.countryName !== '') {
// Make request
}
}
}
}
}
</script>

Vue.js: show profile image in laravel public folder

I am creating commenting system.
And I integrated vue.js in my laravel project.
In my comment area, I want to show user profile image in my laravel
public folder.
But I have no idea how to show image.
What I want to achieve is,
if user has a profile image, I want to show it in comment area. But if
user doesn't have a profile image, I want to show an avatar.
I used vue avatar component so I think I want to use it.
My profile images are stored in public/uploads/profile.
comment.vue
<template>
<div>
<div class="reply-comment" >
<div class="user-comment">
<div class="user">
<!---<img src="{{ $comment->user->img }}" class="image-preview__image">--->
<avatar :username="comment.user.name" :size="45"></avatar>
</div>
<div class="user-name">
<span class="comment-name"><a :href=" '/user/' + 'profile' +'/'+ comment.user.id + '/' ">{{ comment.user.name }}</a></span>
<p>{{ comment.body }}</p>
</div>
</div>
</div>
<div class="reply">
<button #click="addingReply = !addingReply" class="reply-button" :class="{ 'red' : !addingReply, 'black' : addingReply }">
{{ addingReply ? 'Cancel' : 'Add Reply'}}
</button>
</div>
<div class="user-reply-area" v-if="addingReply">
<div class="reply-comment">
<input v-model='body' type="text">
</div>
<button #click="addReply" class="comment-button"><span>Add Reply</span></button>
</div>
<replies ref='replies' :comment="comment"></replies>
</div>
</template>
<script>
import Avatar from 'vue-avatar'
import Replies from './replies.vue'
export default {
components: {
Avatar,
Replies
},
data() {
return {
body: '',
addingReply: false
}
},
props: {
comment: {
required: true,
default: () => ({})
},
post: {
required: true,
default: () => ({})
}
},
methods: {
addReply() {
if(! this.body) return
axios.post(`/comments/${this.post.id}`, {
comment_id: this.comment.id,
body: this.body
}).then(({data})=> {
this.body = ''
this.addingReply = false
this.$refs.replies.addReply(data)
})
.catch(function (error) {
console.log(error.response);
});
}
}
}
</script>
profile.php
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
user.php
public function profile(){
return $this->hasOne(Profile::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
comment.php
protected $with = ['user'];
protected $appends = ['repliesCount'];
web.php
Route::get('results/{post}/comments', 'CommentController#index');
If your database column name for the image file is img then
you can do it like below:
<div class="user" v-if="comment.user.img">
<img :src="'uploads/profile/'+comment.user.img">
</div>
<div class="user" else>
<img :src="default_image_path_here">
</div>
If you are using multiple images for a user you need to add a loop as follow:
<div class="user" v-if="comment.user.img.length > 0">
<span v-for="(item, index) in comment.user.img">
<img :src="'uploads/profile/'+item.your_image_name_column">
</span>
</div>
<div class="user" else>
<img :src="default_image_path_here">
</div>

Property or method "sendResetMail" is not defined on the instance but referenced during render

I'm relatively new to Vue and super stuck with this error message when I try to make this reset email modal work in my Vue project:
Property or method "sendResetMail" is not defined on the instance but
referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by
initializing the property.
I have no idea what I need to do to make this work. I followed the Vue documentation and declared resetEmail in the data option.
ForgotPassword.vue:
<template>
<section>
<a #click="isComponentModalActive = true">
Forgot Password?
</a>
<b-modal :active.sync="isComponentModalActive" has-modal-card>
<modal-form v-bind="resetEmail"></modal-form>
</b-modal>
</section>
</template>
<script>
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
const ModalForm = {
props: ['resetEmail'],
template: `
<form #submit.prevent="sendResetMail">
<div class="modal-card" style="width: auto">
<header class="modal-card-head">
<p class="modal-card-title">Forgot password?</p>
</header>
<section class="modal-card-body">
<b-field label="Email">
<b-input
type="email"
:value="resetEmail"
placeholder="Your email"
required>
</b-input>
</b-field>
</section>
<footer class="modal-card-foot">
<button class="button" type="button" #click="$parent.close()">Close</button>
<button class="button is-primary">Reset</button>
</footer>
</div>
</form>
`
}
export default {
components: {
ModalForm
},
data () {
return {
isComponentModalActive: false,
resetEmail: '',
feedback: null
}
},
methods: {
sendResetMail () {
var auth = firebase.auth()
var emailAddress = this.resetEmail
auth.sendPasswordResetEmail(emailAddress).then(function () {
// Email sent.
console.log('email send')
}).catch(function (error) {
// An error happened.
this.feedback = error.message
console.log(error.message)
})
}
}
}
</script>
This is the file where I use the ForgotPassword.vue component,
Login.vue:
<template>
<section class="section">
<div class="container">
<div class="columns">
<div class="column"></div>
<div class="column is-half">
<div class="box">
<h1 class="title">Login</h1>
<form #submit.prevent="login">
<b-field label="Email" :message="feedback" :type="type">
<b-input placeholder="Email" icon="email" type="email" v-model="email">
</b-input>
</b-field>
<b-field label="Password" :message="feedback" :type="type">
<b-input placeholder="Password" type="password" icon="textbox-password" password-reveal v-model="password">
</b-input>
</b-field>
<button type="submit" class="button is-primary is-fullwidth">Login</button>
<div class="field">
<div class="control">
<p class="control has-text-centered">
<ForgotPassword/>
</p>
</div>
</div>
<div class="field">
<div class="control">
<p class="control has-text-centered">
Don't have an account?
<a href="/register">
<router-link :to="{ name: 'Signup' }">
Signup
</router-link>
</a>
</p>
</div>
</div>
</form>
</div>
</div>
<div class="column"></div>
</div>
</div>
</section>
</template>
<script>
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
import ForgotPassword from '#/components/auth/ForgotPassword'
export default {
name: 'login',
metaInfo: {
// specify a metaInfo.title, this title will be used
title: 'Login',
// all titles will be injected into this template
titleTemplate: '%s | Wterdrops.com'
},
components: {
ForgotPassword
},
data () {
return {
email: null,
password: null,
feedback: null,
type: null
}
},
methods: {
login () {
if (this.email && this.password) {
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(cred => {
this.$router.push({
name: 'Dashboard'
})
})
.catch(err => {
this.feedback = err.message
})
this.feedback = null
} else {
this.feedback = 'Please fill in both fields.'
this.type = 'is-danger'
}
}
}
}
</script>
<style>
.login {
max-width: 400px;
margin-top: 60px;
}
</style>
I would be very grateful if someone can explain to me what I'm missing :)
You are referencing
<form #submit.prevent="sendResetMail">
inside your ModalForm component.
The problem is that this template is going to look for the method sendResetMail on that ModalForm component template when it gets rendered since you the code is referencing it. However this sendResetMail method is not directly associated on that.
You can consider using a mix-in if you need to use the sendResetMail in many places , or maybe just move that method directly to the same component "ModalForm" that is referencing it.
You can also look into for example eventBus to trigger the method by emitting an event.
The simplest option if you only need to call it from the MOdalForm component is to just move the sendResetMail direcly to that component. I believe that would probably fix your issue.

How to Add or Remove Vue.js component dynamically (programmatically or on the fly)

Here is my code, this is just a example code, if the below works then this will help me to build something else that I am working on.
<template>
<div id="wrapper">
<div id="divOne">
<!-- Add or remove component here dynamically -->
</div>
<div id="divTwo">
<!-- Add or remove component here dynamically -->
</div>
<!-- There will be more divs like #divOne #divTwo above -->
<div>
<input type="radio" id="one" value="divOne" v-model="pickedDiv">
<label for="one">One</label>
</div>
<div>
<input type="radio" id="two" value="divTwo" v-model="pickedDiv">
<label for="two">Two</label>
</div>
<button #click="addComponent">Add Component</button>
</div>
</template>
<script>
import SomeComponent from './SomeComponent'
export default {
data() {
return {
pickedDiv: '',
pickedDivPreviously: ''
propItems: ['item1', 'item2']
}
}
methods: {
addComponent () {
//-- This is not working code but I need something like this --//
this.pickedDivPreviously = this.pickedDiv // event not sure how to get previously selected div
const divThatIsPicked = document.getElementById(this.pickedDiv)
const divThatWasPickedPreviously = document.getElementById(this.pickedDivPreviously)
// code here to remove/empty/destroy old component from 'divThatWasPickedPreviously'
divThatWasPickedPreviously.innerHTML = ""
// code here to add new component in 'divThatIsPicked'
divThatIsPicked.appendChild('<some-component :someProp="propItems" #someEvent="someFn">')
}
}
}
</script>
I don't want to distract you from answering actual question but If you are curious about what I am working then check this :) Here I am trying to add new child DIV at the end of the row when any row item is clicked.
I will be more than happy if this is converted to vue than the actual question asked above, as said please don't get distracted from actual question if you find it hard :)
I got help from JamesThomson in forum.vuejs.org, though the solution did not fix my issue but I got to understand the limitation or possibilities of using Vue.js.
JamesThomson says:
Yeah, your example code definitely won’t work. When working with Vue
you need to think in a data oriented way, not DOM oriented (like
jQuery)
Taken from your SO post:
Here I am trying to add new child DIV at the end of the row when any
row item is clicked.
I assume this is your end goal for this topic. A simple example of
this can be achieved like so:
https://codepen.io/getreworked/pen/XZOgbm?editors=1010
let Welcome = {
template: `
<p #click="toggleMsg()">Welcome {{ msg }}!</p>
`,
data () {
return {
msg: 'home'
}
},
methods: {
toggleMsg () {
return this.msg = this.msg === 'home' ? 'back' : 'home';
}
}
}
const App = new Vue({
el: '#app',
data: {
children: [
Welcome
]
},
methods: {
add () {
this.children.push(Welcome);
},
}
});
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<template v-for="(child, index) in children">
<component :is="child" :key="child.name"></component>
</template>
<button #click="add()">Add Another</button>
</div>
or you can use a render function for more flexibility
https://jsfiddle.net/jamesbrndwgn/ku7m1dp0/9/
const Reusable = {
template: '<div>{{ name }} {{ bar }}</div>',
props: {
name: {
type: String
}
},
data () {
return {
bar: 'Bar'
}
}
}
const App = new Vue({
el: '#app',
data: {
items: []
},
methods: {
addComponent () {
const renderComponent = {
render (h) {
return h(Reusable, {
class: ['foo'],
props: {
name: 'Foo'
}
})
}
}
this.items.push(renderComponent)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
<div id="app">
<component v-for="item in items" ref="itemRefs" :is="item" :key="item.name"></component>
<button #click="addComponent">Add Component</button>
</div>
I found one of the other ways that does kinda same as above but work only with old vue.js-1 not with vue.js-2:
var createNewBox = function() {
var MyPartial = Vue.extend({});
window.partial = new MyPartial({
template: '#partial',
data: function() {
return {
txt: 'This is partial'
}
},
methods: {
print: function() {
console.log('this.txt : ' + this.txt)
console.log('main.txt : ' + main.txt)
},
},
})
window.partial.$mount().$appendTo('body')
}
window.main = new Vue({
el: '#main',
data: function() {
return {
txt: 'This is main'
}
},
methods: {
show: function() {
createNewBox()
}
},
})
<script src="https://cdn.bootcss.com/vue/1.0.17/vue.min.js"></script>
<div #click="show" style="width:200px;height:200px;background:#000" id="main">
<template id="partial">
<div style="width:100px;height:100px;background:#ff0" #click.stop="print"></div>
</template>
</div>
this converted to Vue.
https://codepen.io/jacobgoh101/pen/Kojpve
<div id="app">
<div class="parent">
<div class="child" #click="handleChildClick" data-new-child-id="1">1234</div>
<div class="child" #click="handleChildClick" data-new-child-id="2">12341234 </div>
<div class="child" #click="handleChildClick" data-new-child-id="3">123412341234</div>
<div class="child" #click="handleChildClick" data-new-child-id="4">1234</div>
<div class="new-child" v-if="[1,2,3,4].indexOf(showNewChild) > -1">boom</div>
<div class="child" #click="handleChildClick" data-new-child-id="5">12341234</div>
<div class="child" #click="handleChildClick" data-new-child-id="6">123412341234</div>
<div class="child" #click="handleChildClick" data-new-child-id="7">1234</div>
<div class="child" #click="handleChildClick" data-new-child-id="8">12341234</div>
<div class="new-child" v-if="[5,6,7,8].indexOf(showNewChild) > -1">boom</div>
<div class="child" #click="handleChildClick" data-new-child-id="9">123412341234</div>
<div class="new-child" v-if="[9].indexOf(showNewChild) > -1">boom</div>
</div>
</div>
Javascript
new Vue({
el: '#app',
data: {
showNewChild:null
},
methods: {
handleChildClick(e) {
let id = e.target.dataset.newChildId;
id = Number(id);
this.showNewChild = id;
}
}
})

Vue 2: Unable to find method on click event from component

In my vue app i am calling a function on click event, which is located in a component. Here is the component code:
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
#click.stop="addBoard"
class="btn btn-success btn-xs btn-block"
>
Add Board
</button>
</div>
</div>
</div>
`
} )
Here is the vue app instance:
var boardItem = new Vue( {
el: "#board-item",
data: {
boards: [
{ name: 'learning vue 2' }
],
newBoard: [],
viewNewBoard: true
},
methods: {
displayNewBoard: function() {
event.preventDefault()
if( this.viewNewBoard == false ) {
this.viewNewBoard = true
} else {
this.viewNewBoard = false
}
},
addBoard: function() {
console.log( 'add board' )
}
}
} )
Now, when i click on the Add Board button from the above component, it is showing this error:
Uncaught ReferenceError: addBoard is not defined
at click (eval at Xr (vue.min.js:7), :2:455)
at HTMLButtonElement.invoker (vue.min.js:6)
It seems that the button from the component can't find the addBoard method, which is written in the same file!
What i am missing here?
Try:
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
#click.stop="addBoard"
class="btn btn-success btn-xs btn-block"
>
Add Board
</button>
</div>
</div>
</div>
`,
methods: {
addBoard: function(){ console.log('add board');}
}
} )
A few changes here, if you want to share events with components that are not related you must use a new vue instance to fire those events and listen. So based on your code this should help.
window.Event = new Vue();
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
#click.stop="addBoard" // keep this as the name of the local method
class="btn btn-success btn-xs btn-block">
Add Board
</button>
</div>
</div>
</div>
`,
methods:{
addBoard(){
// fire the event, also you can add any params
Event.$emit('callAddBoard',data)
}
}
} )
And the main instance should listen to that event
var boardItem = new Vue( {
el: "#board-item",
data: {
boards: [
{ name: 'learning vue 2' }
],
newBoard: [],
viewNewBoard: true
},
methods: {
displayNewBoard: function() {
event.preventDefault()
if( this.viewNewBoard == false ) {
this.viewNewBoard = true
} else {
this.viewNewBoard = false
}
},
addBoard: function() {
console.log( 'add board' )
}
},
created(){
// here you listen and excute the remote event from component, and apply a local method.
Event.$on('callAddBoard', this.addBoard)
}
} )
As far as I tried this works , and you can send events to any component without the need of passing through the main instance.

Categories