Call method from another component in Vue.js - vue.js

How do I call the method from another component in this scenario? I would like to load additional pice of data from the API once the button is clicked in the component 1 to the component 2.
Thanks
Here are my two components in the seperate files:
compbutton.vue
<template>
<div>
<a href v-on:click="buttonClicked">Change Name</a>
</div>
</template>
<script>
export default {
name: 'compbutton',
methods: {
buttonClicked: function () {
//call changeName here
}
}
}
</script>
compname.vue
<template>
<div>{{name}}</div>
</template>
<script>
export default {
name: 'compname',
data: function () {
return {
name: 'John'
}
},
methods: {
changeName: function () {
this.name = 'Ben'
}
}
}
</script>

You can name the component and then $ref to the method from another componenent.
compbutton.vue
<template>
<div>
<a href v-on:click="buttonClicked">Change Name</a>
</div>
</template>
<script>
export default {
name: "compbutton",
methods: {
buttonClicked: function() {
//call changeName here
this.$root.$refs.compname_component.changeName();
}
}
};
</script>
compname.vue
<template>
<div>{{name}}</div>
</template>
<script>
export default {
name: "compname",
data: function() {
return {
name: "John"
};
},
methods: {
changeName: function() {
this.name = "Ben";
}
},
created() {
// set componenent name
this.$root.$refs.compname_component = this;
}
};
</script>

Alternative answer: you can pass the function you want the child to invoke as a prop from the parent component. Using your example:
compbutton.vue
<template>
<div>
<a href v-on:click="buttonClicked">Change Name</a>
</div>
</template>
<script>
export default {
name: 'compbutton',
props: {
clickHandler: {
type: Function,
default() {
return function () {};
}
}
},
methods: {
buttonClicked: function () {
this.clickHandler(); // invoke func passed via prop
}
}
}
</script>
compname.vue
<template>
<div>{{name}}</div>
<compbutton :click-handler="changeName"></compbutton>
</template>
<script>
export default {
name: 'compname',
data: function () {
return {
name: 'John'
}
},
methods: {
changeName: function () {
this.name = 'Ben'
}
}
}
</script>
Note, in your example, it doesn't appear where you want the 'compbutton' component to be rendered, so in the template for compname.vue, thats been added as well.

You can use a service as a go-between. Usually, services are used to share data but in javascript functions can be treated like data also.
The service code is trivial, just add a stub for the function changeName
changeName.service.js
export default {
changeName: function () {}
}
To have services injected into the components, you need to include vue-injector in the project.
npm install --save vue-inject
or
yarn add vue-inject
and have a register of services,
injector-register.js
import injector from 'vue-inject';
import ChangeNameService from '#/services/changeName.service'
injector.service('changeNameService', function () {
return ChangeNameService
});
then in main.js (or main file may be called index.js), a section to initialize the injector.
import injector from 'vue-inject';
require('#/services/injector-register');
Vue.use(injector);
Finally, add the service to the component dependencies array, and use the service
compname.vue
<script>
export default {
dependencies : ['changeNameService'],
created() {
// Set the service stub function to point to this one
this.changeNameService.changeName = this.changeName;
},
...
compbutton.vue
<script>
export default {
dependencies : ['changeNameService'],
name: 'compbutton',
methods: {
buttonClicked: function () {
this.changeNameService.changeName();
}
}
...
Add a # to the button href to stop page reloads
Change Name
See the whole thing in CodeSandbox

Related

How to access 'layout' or 'page' function directly in component?

How can I access a layout- or page-function directly in a component? Is there a special variable like $root or $parent?
I found a way to do this, but it seems dirty. I saw the component structure using Vue DevTool, and I found the layout is the root's child, so I called the layout's function like this:
this.$root.$children[2].getMap()
Is there a cleaner way?
You could use Vue's provide/inject feature for this. For instance, a page/layout could provide the getMap():
<template>
<MapButton />
</template>
<script>
export default {
name: 'MapPage',
provide() {
return {
getMap() {
return { /* map */ }
}
}
}
}
</script>
...and then any child component on that page/layout could inject the method where needed:
<template>
<button #click="getMap">Get map</button>
</template>
<script>
export default {
name: 'MapButton',
inject: {
getMap: {
default() {
return () => {
console.log('no map')
}
}
}
},
mounted() {
console.log('map', this.getMap())
}
}
</script>

Vue model not updating

When I try to update my custom text-area component's model data this.message='<span id="foo">bar</span> the text and html does not display in the htmltextarea tag like it should, but I can see the update applied in the Vue dev tool's console. I've also tried switching to an object instead of a string and using Vue.set, but this does not work either.
Any suggestions on how to fix this?
The goal with the htmlTextArea component is to get the users text from the htmlTextArea tag (this works), manipulate this text and bind it back to the textarea, but with HTML in it.
Custom text-area component:
<template>
<div contenteditable="true" #input="updateHTML" class="textareaRoot"></div>
</template>
<script>
export default {
// Custom textarea
name: 'htmlTextArea',
props:['value'],
mounted: function () {
this.$el.innerHTML = this.value;
},
methods: {
updateHTML: function(e) {
this.$emit('input', e.target.innerHTML);
}
}
}
</script>
Other component:
<template>
...
<htmlTextArea id="textarea" v-model="message"></htmlTextArea>
...
</template>
<script>
data: {
return {
message: 'something'//this works
}
}
...
methods: {
changeText() {
this.message='<span id="foo">bar</span>'//this does not
}
},
components: {
htmlTextArea
}
</script>
You need to set the value explicitly after the value props change. you can watch for value change.
<template>
<div contenteditable="true" #input="updateHTML" class="textareaRoot"></div>
</template>
<script>
export default {
// Custom textarea
name: "htmlTextArea",
props: ["value"],
mounted: function() {
this.$el.innerHTML = this.value;
},
watch: {
value(v) {
this.$el.innerHTML = v;
}
},
methods: {
updateHTML: function(e) {
this.$emit("input", e.target.innerHTML);
}
}
};
</script>
Change the data property into a function, as you have it defined it is not reactive.
data () {
return {
message: 'something'//this works
}
}
Now when you update the message property in your method, the component will update accordingly.
Reactivity in depth

Why this.$listeners is undefined in Vue JS?

Vue.js version: 2.4.2
Below component always print this.$listeners as undefined.
module.exports = {
template: `<h1>My Component</h1>`,
mounted() {
alert(this.$listeners);
}
}
I register the component and put it inside a parent component.
Can someone tell me why?
You have to understand what $listeners are.
this.$listeners will be populated once there are components that listen to events that your components is emitting.
let's assume 2 components:
child.vue - emits an event each time something is written to input field.
<template>
<input #input="emitEvent">
</input>
</template>
<script>
export default {
methods: {
emitEvent() {
this.$emit('important-event')
console.log(this.$listeners)
}
}
}
</script>
parent.vue - listen to the events from child component.
<template>
<div class="foo">
<child #important-event="doSomething"></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
data() {
return {
newcomment: {
post_id: 'this is default value'
}
}
},
components: { child },
methods: {
doSomething() {
// do something
}
}
}
</script>
With this setup, when you type something to the input field, this object should be written to the console:
{
`important-event`: function () { // some native vue.js code}
}
I added the following alias to my webpack.config.js file and this resolved the issue for me:-
resolve: {
alias: {
'vue$': path.resolve(__dirname, 'node_modules/vue/dist/vue.js')
}
},

How to address the data of a component from within that component?

In a standalone Vue.js script I can mix functions and Vue data:
var vm = new Vue ({
(...)
data: {
number: 0
}
(...)
})
function return100 () {
return 100
}
vm.number = return100()
I therefore have a Vue instance (vm) which data is directly addressable via vm.<a data variable>)
How does such an addressing works in a component, since no instance of Vue is explicitly instantiated?
// the component file
<template>
(...)
</template>
<script>
function return100 () {
return 100
}
export default {
data: function () {
return {
number: 0
}
}
}
// here I would like to set number in data to what return100()
// will return
??? = return100()
</script>
You can achieve the target by using code like this.
<template>
<div>{{ name }}</div>
</template>
<script>
const vm = {
data() {
return {
name: 'hello'
};
}
};
// here you can modify the vm object
(function() {
vm.data = function() {
return {
name: 'world'
};
}
})();
export { vm as default };
</script>
But I really don't suggest you to modify data in this way and I think it could be considered as an anti-pattern in Vuejs.
In almost all the use cases I met, things could be done by using Vue's lifecycle.
For example, I prefer to write code with the style showed below.
<template>
<div>{{ name }}</div>
</template>
<script>
export default {
data() {
return {
name: 'hello'
};
},
mounted() {
// name will be changed when this instance mounted into HTML element
const vm = this;
(function() {
vm.name = 'world';
})();
}
};
</script>

how to call a method on the component by clicking Vue.js?

I am use component of the dialog window dialog.vue from vue-mdl package
<template>
<div class="mdl-dialog-container" v-show="show">
<div class="mdl-dialog">
<div class="mdl-dialog__title">{{title}}</div>
<div class="mdl-dialog__content">
<slot></slot>
</div>
<div class="mdl-dialog__actions" :class="actionsClasses">
<slot name="actions">
<mdl-button class="mdl-js-ripple-effect" #click.native.stop="close">Close</mdl-button>
</slot>
</div>
</div>
</div>
</template>
<script>
import mdlButton from './button.vue'
import createFocusTrap from 'focus-trap'
export default {
components: {
mdlButton
},
computed: {
actionsClasses () {
return {
'mdl-dialog__actions--full-width': this.fullWidth
}
}
},
data () {
return {
show: false
}
},
props: {
title: {
type: String
},
fullWidth: Boolean
},
mounted () {
this._focusTrap = createFocusTrap(this.$el)
},
methods: {
open () {
this.show = true
this.$nextTick(() => this._focusTrap.activate())
this.$emit('open')
},
close () {
this.show = false
this._focusTrap.deactivate()
this.$emit('close')
}
}
}
</script>
I want to bring a dialog window to the other component
<mdl-dialog></mdl-dialog>
<button class="mdl-button mdl-js-button mdl-button--raised">Click me</button>
I found no information on how to call a method of one component within the other. All examples are mainly used props. Tell me how to do it?
How can I call a method open() in <mdl-dialog></mdl-dialog>?
Since they're not parent child you'd want to use an event bus. Since you're using .vue files you can create a file called bus.js like
import Vue from 'vue'
export default new Vue()
Then, import that wherever you need to emit and listen for centralized events. Here's a quick example:
// SomeComponent.vue
import bus from './bus.js'
export default {
methods: {
log (msg) {
console.log(msg)
}
},
created () {
bus.$on('someEvent', this.log)
}
}
Then in another component you can do like...
// AnotherComponent.vue
import bus from './bus.js'
export default {
methods: {
emitClick (msg) {
bus.$emit('Hello from AnotherComponent.vue')
},
},
}
You can read up a bit more about it here: https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
You can create below helper method in methods in your parent component:
getChild(name) {
for(let child of this.$children) if (child.$options.name==name) return child;
},
And call child component method in this way:
this.getChild('mdl-dialog').open();
I don't test it for Vue>=2.0