VueJS: v-on:click not working on clicking the <button> - javascript

I have a Vue app configured by NuxtJS.
I have the following template and worker methods that should be called upon clicking the button. But they are not being called.
<template>
<button class="btn google-login" id="google-login" #click.native="googleLogin">
<img src="~assets/google-icon.svg" alt />
Login with Google
</button>
</template>
<script>
import firebase from "firebase";
export default {
data() {
return {
showPassword: false,
checkbox1: false
};
},
mounted: function() {
console.log(firebase.SDK_VERSION);
},
methods: {
googleLogin: function(event) {
console.log('Reached inside the function');
let googleProvider = new firebase.auth.GoogleAuthProvider();
googleProvider.addScope(
"https://www.googleapis.com/auth/contacts.readonly"
);
firebase.auth().useDeviceLanguage();
console.log(googleProvider);
}
}
};
</script>
I have the method inside the methods object. I have tried multiple solutions v-on:click, #click, #click.prevent but none seem to be working

.native event modifier is used with elements when you are trying listen any event happening in the child Component from the root Component.
For example you have a component button-counter, and your parent component need to listen to the click event happening in the button-counter component.
In your case you just neeed to trigger click event using #click="googleLogin"
Official Documentation
Read More
Sample implementation
new Vue({
el: "#app",
name: "MyApp",
components: {
'button-counter': {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
},
},
methods: {
googleLogin: function (event) {
console.log('Reached inside the function');
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<div id="app">
<button class="btn google-login" id="google-login" #click="googleLogin">
Login with Google
</button>
<button-counter #click.native="googleLogin" />
</div>

You need to trigger the click event this way.
#click="googleLogin"

Related

child component emit an custom event, but parent component's listener not triggered

I'm registered a child component in Vue, the child will emit an custom event, but the parent component's listener not triggered.
<template id="add-item-template">
<div class="input-group">
<input #keyup.enter="addItem" v-model="newItem" >
<span class="input-group-btn">
<button #click="addItem" type="button">Add!</button>
</span>
</div>
</template>
<div id="app" class="container">
<h2>{{ title }}</h2>
<add-item-component v-on:itemAdd="addAItem"></add-item-component>
</div>
Vue.component('add-item-component', {
template: '#add-item-template',
data: function () {
return {
newItem: ''
};
},
methods: {
addItem() {
this.$emit('itemAdd');
console.log("itemAdd In add-item-component");
}
}
});
new Vue({
el: '#app',
data: {
title: 'Welcome to Vue'
},
methods: {
addAItem: function () {
console.log("In #app, addAItem()!");
}
}
});
The "itemAdd In add-item-component" log show in console, but "In #app, addAItem()!" log not, the #app's method addAItem not invoked.
The problem is that custom events should not be named with camelCase. If you look at the error message in the console, it tells you:
Event "itemadd" is emitted in component but the handler is registered for "itemAdd"
The component is emitting a lowercase version even though you've used camelCase to name it. Renaming to all lowercase or kebab-case will fix it.
In the parent template:
<add-item-component #itemadd="addAItem">
Emitting from the child:
this.$emit('itemadd');
This is discussed a bit with Evan You (Vue creator) here

VueJS 2 show some HTML if a Function prop was passed

Question
In VueJS 2 how do you show some HTML if a Function prop was passed to the component.
Example
<template>
<div v-if="backBtn" #click="$emit('backBtn')">Back Button</div>
</template>
<script>
export default {
props: {
backBtn: Function
}
}
</script>
I can do this by passing a separate prop to key the v-if off of but I'm trying to do this will the one prop.
I created a Fiddle for this issue here
that should work,
you can add more definition with !== undefined
<template>
<div v-if="backBtn !== undefined" #click="$emit('backBtn')">Back Button</div>
</template>
<script>
export default {
props: {
backBtn: {
type: Function,
},
}
}
</script>
but as mentioned, that should work already, so you error may be somewhere else.
after seeing your code, I see what the issue is. it's a case issue
use :back-btn instead of :backBtn
this happens only if you're using vue runtime only (without the compilation)
read more here:
https://v2.vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
you can solve it also by passing the function only
https://jsfiddle.net/rz6hyd7b/7/
Vue.component('my-btn', {
props: {
backbtn: {
type: Function
}
},
template: `
<div>
<div v-if="backbtn" #click="backbtn">Back Button</div>
</div>
`
})
var vm = new Vue({
el: '#app',
components: 'my-btn',
methods: {
btnClicked: function(){
console.log('adsf')
}
},
template: `
<div>
Show Btn => <my-btn :backbtn="btnClicked"></my-btn>
</br>
Hidden Btn => <my-btn></my-btn>
</div>
`
});

Hook=componentUpdated of Vue directive not triggered

I just met one issue, if one component only update its own data, it will not trigger the hook=componentUpdated of the directive at the parent component.
As Vue official Guide said:
componentUpdated: called after the containing component’s VNode and
the VNodes of its children have updated.
It seems componentUpdated should be triggered.
Did I do something wrong? or misunderstand something?
At below demo, hit Click Me! button then you will see componentUpdated is not called.
But when click change data (execute similar behavior with click me!, the difference is it changes the data at parent component), it will trigger correctly.
Many thanks for any.
Vue.config.productionTip = false
Vue.component('child', {
template: `<div>{{point}}
<span style="background-color:gray;font-weight:bold;color:red">
-{{mytest}}
</span>
<button #click="plusOne()">Click me!</button>
</div>`,
props: ['point'],
data(){
return {
mytest: 1
}
},
updated: function () {
console.log('updated component=child')
},
methods: {
plusOne() {
this.mytest += 1
}
}
})
let vMyDirective = {}
vMyDirective.install = function install (Vue) {
Vue.directive('my-directive', {
inserted: function () {
console.log('!!!directive for inserted')
},
bind: function bind (el, binding, vnode) {
console.log('!!!directive for bind')
},
componentUpdated: function componentUpdated (el, binding, vnode) {
console.log('!!!directive for component updated')
},
update: function () {
console.log('!!!directive for update')
}
})
}
Vue.use(vMyDirective)
new Vue({
el: '#app',
data() {
return {
testValues: ['label a', 'label b'],
testIndex: 1
}
},
methods:{
pushArray: function() {
this.testValues.push('label c')
},
changeData: function () {
this.testIndex += 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button v-on:click="pushArray()">Add one Child!!!</button>
<button v-on:click="changeData()">Change Data - {{testIndex}}</button>
<div v-my-directive>
<child v-for="(item, index) in testValues" :key="index" :point="item"></child>
</div>
</div>
Based on Vue Team Feedback, it is not one issue on the hook=componentUpdated, it is my misunderstanding on the words.
For the prerequisite of the hook=comopnentUpdated is triggered, it is the VNode which the directive binds to already changed. That means if only child VNode changes, Vue will not catch it probably like what #Jacob Goh said in the comments (only flows one way).
So componentUpdated doesn't means it will detect child components are updated or not, it only means when will be triggered.

Vue.js: Simple click function not firing

I have a very simple app:
<div id="show_vue">
<page-change page="bio" #click="changeThePage"></page-change>
<page-change page="health" #click="changeThePage"></page-change>
<page-change page="finance" #click="changeThePage"></page-change>
<page-change page="images" #click="changeThePage"></page-change>
</div>
Vue.component("page-change", {
template: "<button class='btn btn-success'>Button</button>",
props: ["page"]
})
var clients = new Vue({
el: '#show_vue',
data: {
currentRoute: window.location.href
},
methods: {
changeThePage: function() {
console.log("this is working")
}
}
})
...but when I click the <page-change></page-change> button, nothing is logged to the console. I know I'm missing something simple but I'm not getting any errors.
How do I make my click fire changeThePage
When you do :
<page-change page="bio" #click="changeThePage"></page-change>
That means that your are waiting page-change component emit the click event.
Best solution (thanks to #aeharding) : Use .native event modifier
<page-change page="bio" #click.native="changeThePage"></page-change>
Solution 1 : emit click event from child component :
Vue.component("page-change", {
template: "<button #click='clicked' class='btn btn-success'>Button</button>",
props: ["page"],
methods: {
clicked: function(event) {
this.$emit('click', this.page, event);
}
}
})
For information event is the default value passed by Vue for native event like click : DOM event
Solution 2 : emit directly from parent component :
Vue.component("page-change", {
template: "<button class='btn btn-success'>Button {{ page }}</button>",
props: ["page"]
})
var clients = new Vue({
el: '#show_vue',
data: {
currentRoute: window.location.href,
pages: [
'bio', 'health',
'finance', 'images'
]
},
methods: {
changeThePage: function(page, index) {
console.log("this is working. Page:", page, '. Index:', index)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="show_vue">
<span v-for="(page, index) in pages" :key="index+page"
#click="changeThePage(page, index)">
<page-change :page="page"></page-change>
</span>
</div>
The best way to do this is to use the .native event modifier.
For example:
<my-custom-component #click.native="login()">
Login
</my-custom-component>
Source: https://v2.vuejs.org/v2/guide/components.html#Binding-Native-Events-to-Components
apparently v-on:click seems to work better with the .native event modifier.
try page="bio" v-on:click.native="changeThePage()"></page-change>. It worked for me.

Call a Vue.js component method from outside the component

Let's say I have a main Vue instance that has child components. Is there a way of calling a method belonging to one of these components from outside the Vue instance entirely?
Here is an example:
var vm = new Vue({
el: '#app',
components: {
'my-component': {
template: '#my-template',
data: function() {
return {
count: 1,
};
},
methods: {
increaseCount: function() {
this.count++;
}
}
},
}
});
$('#external-button').click(function()
{
vm['my-component'].increaseCount(); // This doesn't work
});
<script src="http://vuejs.org/js/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
<my-component></my-component>
<br>
<button id="external-button">External Button</button>
</div>
<template id="my-template">
<div style="border: 1px solid; padding: 5px;">
<p>A counter: {{ count }}</p>
<button #click="increaseCount">Internal Button</button>
</div>
</template>
So when I click the internal button, the increaseCount() method is bound to its click event so it gets called. There is no way to bind the event to the external button, whose click event I am listening for with jQuery, so I'll need some other way to call increaseCount.
EDIT
It seems this works:
vm.$children[0].increaseCount();
However, this is not a good solution because I am referencing the component by its index in the children array, and with many components this is unlikely to stay constant and the code is less readable.
In the end I opted for using Vue's ref directive. This allows a component to be referenced from the parent for direct access.
E.g.
Have a component registered on my parent instance:
var vm = new Vue({
el: '#app',
components: { 'my-component': myComponent }
});
Render the component in template/html with a reference:
<my-component ref="foo"></my-component>
Now, elsewhere I can access the component externally
<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>
See this fiddle for an example: https://jsfiddle.net/0zefx8o6/
(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)
Edit for Vue3 - Composition API
The child-component has to return the function in setup you want to use in the parent-component otherwise the function is not available to the parent.
Note: <sript setup> doc is not affacted, because it provides all the functions and variables to the template by default.
You can set ref for child components then in parent can call via $refs:
Add ref to child component:
<my-component ref="childref"></my-component>
Add click event to parent:
<button id="external-button" #click="$refs.childref.increaseCount()">External Button</button>
var vm = new Vue({
el: '#app',
components: {
'my-component': {
template: '#my-template',
data: function() {
return {
count: 1,
};
},
methods: {
increaseCount: function() {
this.count++;
}
}
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component ref="childref"></my-component>
<button id="external-button" #click="$refs.childref.increaseCount()">External Button</button>
</div>
<template id="my-template">
<div style="border: 1px solid; padding: 2px;" ref="childref">
<p>A counter: {{ count }}</p>
<button #click="increaseCount">Internal Button</button>
</div>
</template>
For Vue2 this applies:
var bus = new Vue()
// in component A's method
bus.$emit('id-selected', 1)
// in component B's created hook
bus.$on('id-selected', function (id) {
// ...
})
See here for the Vue docs.
And here is more detail on how to set up this event bus exactly.
If you'd like more info on when to use properties, events and/ or centralized state management see this article.
See below comment of Thomas regarding Vue 3.
You can use Vue event system
vm.$broadcast('event-name', args)
and
vm.$on('event-name', function())
Here is the fiddle:
http://jsfiddle.net/hfalucas/wc1gg5v4/59/
A slightly different (simpler) version of the accepted answer:
Have a component registered on the parent instance:
export default {
components: { 'my-component': myComponent }
}
Render the component in template/html with a reference:
<my-component ref="foo"></my-component>
Access the component method:
<script>
this.$refs.foo.doSomething();
</script>
Say you have a child_method() in the child component:
export default {
methods: {
child_method () {
console.log('I got clicked')
}
}
}
Now you want to execute the child_method from parent component:
<template>
<div>
<button #click="exec">Execute child component</button>
<child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
</div>
</template>
export default {
methods: {
exec () { //accessing the child component instance through $refs
this.$refs.child.child_method() //execute the method belongs to the child component
}
}
}
If you want to execute a parent component method from child component:
this.$parent.name_of_method()
NOTE: It is not recommended to access the child and parent component like this.
Instead as best practice use Props & Events for parent-child communication.
If you want communication between components surely use vuex or event bus
Please read this very helpful article
This is a simple way to access a component's methods from other component
// This is external shared (reusable) component, so you can call its methods from other components
export default {
name: 'SharedBase',
methods: {
fetchLocalData: function(module, page){
// .....fetches some data
return { jsonData }
}
}
}
// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];
export default {
name: 'History',
created: function(){
this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
}
}
Using Vue 3:
const app = createApp({})
// register an options object
app.component('my-component', {
/* ... */
})
....
// retrieve a registered component
const MyComponent = app.component('my-component')
MyComponent.methods.greet();
https://v3.vuejs.org/api/application-api.html#component
Here is a simple one
this.$children[indexOfComponent].childsMethodName();
I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component
import myComponent from './MyComponent'
and then call any method of MyCompenent
myComponent.methods.doSomething()
Declare your function in a component like this:
export default {
mounted () {
this.$root.$on('component1', () => {
// do your logic here :D
});
}
};
and call it from any page like this:
this.$root.$emit("component1");
If you're using Vue 3 with <script setup> sugar, note that internal bindings of a component are closed (not visible from outside the component) and you must use defineExpose(see docs) to make them visible from outside. Something like this:
<script setup lang="ts">
const method1 = () => { ... };
const method2 = () => { ... };
defineExpose({
method1,
method2,
});
</script>
Since
Components using are closed by default
Sometimes you want to keep these things contained within your component. Depending on DOM state (the elements you're listening on must exist in DOM when your Vue component is instantiated), you can listen to events on elements outside of your component from within your Vue component. Let's say there is an element outside of your component, and when the user clicks it, you want your component to respond.
In html you have:
Launch the component
...
<my-component></my-component>
In your Vue component:
methods() {
doSomething() {
// do something
}
},
created() {
document.getElementById('outsideLink').addEventListener('click', evt =>
{
this.doSomething();
});
}
I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!
In the Vue Component, I have included something like the following:
<span data-id="btnReload" #click="fetchTaskList()"><i class="fa fa-refresh"></i></span>
That I use using Vanilla JS:
const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();

Categories