onclick event not firing in vue.js - javascript

I have the following Vue.js template :
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:click="onSubmit"></ti-button>
</div>
</script>
<script type="text/x-template" id="ti-button">
<button class="mdc-button mdc-button--raised" v-bind:title="button.name">{{button.name}}</button>
</script>
script
Vue.component('ti-page-inquire', {
props: ['page'],
template: '#ti-page-inquire',
methods : {
onSubmit : function() {
alert(1);
}
}
});
Vue.component('ti-button', {
props: ['button'],
template: '#ti-button',
mounted: function () {
// ripple on button
mdc.ripple.MDCRipple.attachTo(this.$el);
}
});
when I click on my custom button, nothing happens. I think it's because its looking for onSubmit in the ti-button component, but how do I get it to look in the ti-page-inquire component?

Components are black boxes you should catch all events inside it and emit them to the outer world.
Fiddle example
Vue.component('ti-button', {
props: ['button'],
template: '#ti-button',
mounted: function () {
// ripple on button
mdc.ripple.MDCRipple.attachTo(this.$el);
},
methods: {
buttonClicked: function() {
this.$emit('button-clicked');
}
}
});
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:button-clicked="onSubmit"></ti-button>
</div>
</script>
<script type="text/x-template" id="ti-button">
<button class="mdc-button mdc-button--raised" v-bind:title="button.name" #clicked="buttonClicked">{{button.name}}</button>
</script>

This might be because you need to listen for a native click event. So you need to use the .native modifier ..
<ti-button v-bind:button="page.button" v-on:click.native="onSubmit"></ti-button>
This will only work if the button is the root element of your ti-button component. Otherwise you'll have to pass your event listeners to your button in the ti-button component like this ..
<button v-on="$listeners" ...> ... </button>

Try to emit an event from ti-button component to the parent one by using this.$emit function :
Vue.component('ti-button', {
props: ['name'],
template: '#vButton',
data: {
name: 'hi'
},
methods: {
submit() {
this.$emit('submit')
}
}
});
<template id="vButton">
<button v-bind:title="name" #click="submit">{{name}}</button>
</template>
the emitted event submit it called in the parent component like v-on:submit="onSubmit" and handled using onSubmit method:
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:submit="onSubmit"></ti-button>
</div>
</script>
Vue.component('ti-page-inquire', {
props: ['page'],
template: '#ti-page-inquire',
methods : {
onSubmit : function() {
alert(1);
}
}
});
Sometimes you need also to emit some parameters, so you could do it like :
this.$emit('submit',params)
params could be of any type

Related

Passing custom emited events as props to a new created component in VueJs

My app consists of:
A component named
<consl :output="output" #submit-to-vue><consl>
which contains an input that calls a submit() method when enter key is pressed.
<div>
<output v-html="output"></output>
<div id="input-line" class="input-line">
<div class="prompt">{{ prompt }}</div>
<div>
<input class="cmdline" autofocus
v-model.trim="command"
#keyup.enter="submit"
:readonly="submited" />
</div>
</div>
Then the method submit() emits an event #submit-to-vue to parent method submitv() that create an instance of the same component and adds it to the DOM.
//........
methods: {
submit: function () {
this.$emit('submit-to-vue')
this.submited = true
}
},
and
//......
methods: {
submitv: function () {
var ComponentClass = Vue.extend(consl)
var instance = new ComponentClass({
propsData: { output: this.output }
})
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)
What I want to accomplish ?
I want to create a new consl component and add it to the DOM every time the old one is submited. (I want my app to emulate a terminal)
The problem
When submitted the new created component does not contain the #submit-to-vue event listener, which make it unable to recall the submitv() method.
Questions
How can I solve this problem ?
Is this the proper way to do things in VueJs or is there a more elegent way ?
In parent component, declare one data property=childs, it will includes all childs already created.
So once parent component receives the event=submit-to-vue, then add one new child to this.childs
Finally uses v-for to render these child components.
The trick: always consider the data-driven way, doesn't manipulate dom directly as possible.
below is one simple demo :
Vue.config.productionTip = false
Vue.component('child', {
template: `
<div>
<div>Label:<span>{{output}}</span></div>
<div>Value:<span>{{command}}</span></div>
<div id="input-line" class="input-line">
<div class="prompt">{{ prompt }}</div>
<div>
<input class="cmdline" autofocus
v-model.trim="command"
#keyup.enter="submit"
:readonly="submited" />
</div>
</div>
</div>`,
props: ['output'],
data() {
return {
submited: false,
command: ''
}
},
computed: {
prompt: function () {
return this.submited ? 'Already submitted, input is ready-only now' : ''
}
},
methods: {
submit: function () {
this.$emit('submit-to-vue')
this.submited = true
}
}
})
app = new Vue({
el: "#app",
data: {
childs: [{'output':'default:'}]
},
methods: {
addChild: function () {
this.childs.push({'output': this.childs.length})
}
}
})
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div>
<ul>
<li v-for="(child, index) in childs" :key="index">
<child :output="child.output" #submit-to-vue="addChild()"></child>
</li>
</ul>
</div>
</div>

Handle key press by function in VueJs

in my component I am using VueStrap's modal like this:
<template>
<modal-window v-model="show" v-on:keyup="keyHandler($event)" #ok="submit()" #cancel="cancel()" #closed="close()" ... >
...
</modal-window>
...
</template>
<script>
...
methods: {
keyHandler (event) {
console.log(event);
}
},...
</script>
I want handle key press when that modal is opened and ensure submit modal when enter pressed or close modal when esc pressed.
I added custom function keyHandler which is unfortunately never fired. Can you tell me how to fix code to handle key press in that function? Or when is better way how to close and submit vue strap modal I will be grateful for advice. Thank you.
You can attach your event handler to window, that way you can receive all key events and act accordingly depending on your modal's state:
Vue.component('modal', {
template: '<div>test modal</div>',
});
new Vue({
el: "#app",
created() {
window.addEventListener('keydown', (e) => {
if (e.key == 'Escape') {
this.showModal = !this.showModal;
}
});
},
data: {
showModal: true
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<modal v-show="showModal"></modal>
</div>
easiest way
<input v-on:keyup.13="whatkey()" type="text"> <br>
looks for if the enter key is pressed then fires a method called whatkey.
Alternatively, you may want to consider using the v-hotkey directive for key input in Vue (docs, github). This will keep your code relatively clean and simple if you must consider several different key inputs.
1.  Install it:
npm i --save v-hotkey
 Have Vue 'use' it:
import VueHotkey from "v-hotkey";
Vue.use(VueHotkey);
3.  Apply it to your Vue components, like so:
<template>
<modal-window ... v-hotkey="keymap">
...
</modal-window>
</template>
<script>
...
data() {
return {
showModal: false
};
},
computed: {
keymap() {
return {
"esc": this.toggleModal
};
}
},
methods: {
toggleModal() {
this.showModal = !this.showModal;
}
}
</script>

Vue event handler on dynamically inserted string does not work

This is my code:
<template>
<div>
<div v-html="data"></div> <button v-on:click="replace">Click Me to replace div contents</button>
</div>
</template>
<script>
export default {
data() {
return {
data: "I will be replaced once you click on button"
}
},
methods: {
clickMe() {
alert("worked");
},
replace(){
this.data = "Why does click me not work? It is loaded from server via ajax <a href v-on:click.prevent='clickMe'>Click Me</a>";
}
}
};
</script>
Here if I click on Click Me to replace div contents the content is replaced but the event handler clickMe does not fire. This data would come from server and I need to compile this string and use it from within the Vue's context so Vue can handle events etc.
How can I have the dynamic string downloaded from server work? I am using Vue 2.
Since v-html isn't compiled you will have to create a mini component like this to get around the issue:
new Vue({
el: '#app',
data () {
return {
data: ``
}
},
computed: {
compiledData () {
return {
template: `<p>${this.data}</p>`
}
}
},
methods: {
replace () {
this.data = `Now click on me <a href='#' #click.prevent='alert("yo")'> here </a>`
}
}
})
<script src="https://unpkg.com/vue#2.5.3/dist/vue.min.js"></script>
<div id="app">
<component :is="compiledData" ></component>
<button v-on:click="replace">Click Me to replace div contents</button>
</div>
The above code compiles the string content and thus you can run/execute the function as intended
Other solution using Vue components (codepen):
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div id="someId"></div> <button v-on:click="replace">Click Me to replace div contents</button>
<component :is="currentView"></component>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
currentView: null
},
methods:{
replace: function(){
var templateFromServer = getTemplate();
var comp=Vue.component('template-from-server', {
template: templateFromServer,
methods:{
clickMe:function (){
console.log("click");
}
}
});
this.currentView = comp;
}
}
});
function getTemplate(){
return "<a href v-on:click.prevent='clickMe'>Click Me</a>"
}
</script>
v-html is not compiled as a Vue template. From the docs:
Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates. If you find yourself trying to compose templates using v-html, try to rethink the solution by using components instead.
see: https://v2.vuejs.org/v2/api/#v-html
You can not render VueJS code from a html string.
You can solve this issue by using v-if
<div>
<div v-if="data">I will be replaced once you click on button</div>
<div v-else>Why does click me not work? It is loaded from server via ajax <a href #click.prevent='clickMe'>Click Me</a></div>
<button #click="replace">Click Me to replace div contents</button>
</div>
<script>
export default {
data() {
return {
data: true
}
},
methods: {
clickMe() {
alert("worked");
},
replace(){
this.data = !this.data;
}
}
};
You can call normal javascript function from string but not vuejs function so onclick event would also work.

on click button within v-for change this attribute vue js

I am trying to create an 'add friend' button like facebook. When click this 'add friend' button it changes to 'friend request sent' button. I have tried following approach which doesn't work:
html:
<div v-for="(friend, index) in friends">
<div v-if="friend.sentRequest">
<button class='disabled'>Friend request sent</button>
</div>
<div v-else>
<button #click="addFriend(friend)">Add friend</button>
</div>
</div>
script:
<script>
export default {
data() {
return {
friends: [],
}
},
methods: {
addFriend(friend) {
friend.sentRequest = true;
}
}
}
</script>
I need help to fix this. Thanks in advance.
When you want to define property for existing object you should to use this.$set(target, key, value).
In this case use:
methods: {
addFriend(friend) {
this.$set(friend, 'sentRequest', true);
}
}

Property or method "value" is not defined on the instance in vue js 2 nested component

I wrote a basic vue js 2 basic example to test nested components.
Below is components and template structure.
Vue.component('form-com', {
template: '#form',
props: ['value'],
methods: {
onInput: function (event) {
this.$emit('input', event.target.value);
}
}
});
Vue.component('message-com', {
template: '#message',
data: function () {
return {
msg: 'Hello'
}
},
props: ['user']
});
Vue.component('welcome-com', {
template: '#welcome',
data: function () {
return {
user: 'ahmad'
}
}
});
new Vue({
el: '#container'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<!--Form Template-->
<template id="form">
<div>
<div class="form-control">
<label>Enter Your Name:</label>
<input type="text" v-bind:value="value" :input="onInput">
</div>
</div>
</template>
<!--Hello Message Template-->
<template id="message">
<div>
<h3>{{msg}} {{user}}</h3>
</div>
</template>
<template id="welcome">
<div>
<form-com :value="value"></form-com>
<br>
<message-com :user="user"></message-com>
</div>
</template>
<div id="container">
<welcome-com></welcome-com>
</div>
But when run app in browser this error is shown:
[Vue warn]: Property or method "value" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
found in
---> <WelcomeCom>
<Root>
what is problem?
Update:
I just Rewrite this Fiddle from one of chapters of Learning Vue.js 2. I just rename some parameters and component and templates names. but when I copy main fiddle to my code all things worked.
In your form-com component you can set up a v-model which binds the input value and set up a watcher to observer the changes in the input which in turn emits an custom-event which telss the parent comonent that a change has taken place.
Vue.component('form-com', {
template: '#form',
data(){
return{
myInput:''
}
},
watch: {
myInput: function (inputVal) {
this.$emit('input', inputVal);
}
}
});
Vue.component('message-com', {
template: '#message',
data: function () {
return {
msg: 'Hello'
}
},
props: ['user']
});
Vue.component('welcome-com', {
template: '#welcome',
data: function () {
return {
user: 'ahmad'
}
},
methods:{
updateUser(value){
this.user = value;
}
}
});
new Vue({
el: '#container'
})
You can listen to the events emitted from the child **form-com ** component using v-on:input or shorthand #input directly in the parent template (welcome component) where the child component is used.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<!--Form Template-->
<template id="form">
<div>
<div class="form-control">
<label>Enter Your Name:</label>
<input type="text" v-model="myInput">
</div>
</div>
</template>
<!--Hello Message Template-->
<template id="message">
<div>
<h3>{{msg}} {{user}}</h3>
</div>
</template>
<template id="welcome">
<div>
<form-com #input="updateUser($event)" ></form-com>
<br>
<message-com :user="user"></message-com>
</div>
</template>
<div id="container">
<welcome-com></welcome-com>
</div>
Here is the jsFiddle
If you don't want to use a watcher then you can do it using computed setter . Have a look at the fiddle which is using a computed-setter
You are missing in your Component 'welcome-com' the value object:
Vue.component('welcome-com', {
template: '#welcome',
data: function () {
return {
value: '',
user: 'ahmad'
}
}
});

Categories

Resources