How to call methods in App.vue from the vue components - javascript

I have a vue component and a vue element declaration as given below
Vue.component('todo-item', {
template: '<li>This is a todo</li>'
methods: {
test: function() {
// I am getting an error here
app.aNewFunction();
}
}
})
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
aNewFunction: function() {
alert("inside");
}
}
})
How to call a method in vue app from the vue component?

You can execute root instance method like this: this.$root.methodName()
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
this.$root.aNewFunction();
}
},
mounted() {
this.test();
}
})
new Vue({
el: '#app',
template: '<todo-item></todo-item>',
methods: {
aNewFunction: function() {
alert("inside");
}
}
})

Another solution which I think it's more accorded with Vuejs architecture, it's to use events listener & emitter between child-component and its parent to make communications.
Check this simple fiddle as a vision
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
console.log('Emmit this Event.');
this.$emit('yourevent');
}
},
created() {
this.test();
}
});
new Vue({
el: '#vue-app',
data: {
'message': '',
},
methods: {
aNewFunction(event) {
console.log('yourevent Is Triggered!');
this.message = 'Do Stuff...';
},
}
});

Related

How do I call a Vue.js function from an external JavaScript file?

I have to call a Vue.js function from an external JavaScript file, but it's not working. Below I have given the code that I have tried.
// external js file
import vm from './vue.js';
function callingVuejsFunction(data) {
this.vm.displayData()
}
// Vuejs file
var vm = new Vue({
el: '#app',
data: {
firstname : '' ,
lastname : ''
},
methods:{
displayData: function( ) {
alert()
}
}
})
You can use vm.$options.methods.displayData():
var vm = new Vue({
el: '#app',
data: {
firstname: '',
lastname: ''
},
methods: {
displayData: function(msg) {
alert(msg)
}
}
})
vm.$options.methods.displayData('I was called externally!')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
export default {
methods:{
my_function(){
alert('vue function trigger!!!')
}
},
created () {
let _this = this
window.addEventListener('ready', function() {
_this.my_function()
})
}
}
Here is the perfect example of calling a vue method from javascript.

Vue - non parent child communication

When reading Vue document
Non parent-child communication
For practice, I tried to build an example to see if it works, below is my code:
I build two component and tried to use Vue instance bus to transport message from dudi-station to dudo-station while on-click, but it's not working.
Can anyone help? Thanks!
Vue.component('dudi-station', {
template: '<div #click="sentMsg">{{dudiMsg}}</div>',
data: function() {
return {
dudiMsg: 'Dudi!!',
}
},
methods: {
sentMsg: function() {
bus.$emit('callout', this.dudiMsg);
},
}
});
Vue.component('dudo-station', {
template: '<div>{{dudoMsg}}</div>',
data: function() {
return {
dudoMsg:'',
}
},
created: function() {
bus.$on('callout', function(value) {
this.dudoMsg = value;
console.log(value);
});
}
});
var bus = new Vue();
new Vue({
el: '#app',
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<dudi-station></dudi-station>
<dudo-station></dudo-station>
</div>
Use arrow function as event handler when receiving message in component from another component. It will help you with "this" keyword scope.
bus.$on('callout', function(value) {
this.dudoMsg = value;
console.log(value);
});
instead of this use it as below
bus.$on('callout', (value) => {
this.dudoMsg = value;
console.log(value);
});
Because in this statement:
bus.$on('callout', function(value) {
this.dudoMsg = value;
this this is not mean your vue instance.
You need to use arrow function to make sure that 'this' means the vue instance.
Like below:
Vue.component('dudi-station', {
template: '<div #click="sentMsg">{{dudiMsg}}</div>',
data: function() {
return {
dudiMsg: 'Dudi!!',
}
},
methods: {
sentMsg: function() {
bus.$emit('callout', this.dudiMsg);
},
}
});
Vue.component('dudo-station', {
template: '<div>{{dudoMsg}}</div>',
data: function() {
return {
dudoMsg:'',
}
},
created: function() {
bus.$on('callout',value => {
this.dudoMsg = value;
console.log(value);
});
}
});
var bus = new Vue();
new Vue({
el: '#app',
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<dudi-station></dudi-station>
<dudo-station></dudo-station>
</div>

How to fetch data from server in vue js?

I am trying to fetch data from the server using Vue + Vuex + Vue resource.On button click I want to hit Http request and show in list format .I tried like that.Here is my code
https://plnkr.co/edit/EAaEekLtoiGPvxkmAtrt?p=preview
// Code goes here
var store = new Vuex.Store({
state: {
Item: []
},
mutations: {
getItems: function (state) {
}
},
actions: {
fetchData:function (context) {
this.$http.get('/data.json', function(v1users)
{
// this.$set('v1_user',v1users);
});
}
}
})
var httprequest = Vue.extend({
"template": '#http_template',
data: function () {
return {
items: store.state.Item
}
},
methods: {
fetchData: function () {
store.dispatch('fetchData')
},
}
})
Vue.component('httprequest', httprequest);
var app = new Vue({
el: '#App',
data: {},
})
;
any udpdate?
Try using Vue.http.get instead of this.$http.get.
Vuex doesn't have access to $http directly from instance.

How to get data from server before component is mounted vue2.0

I've got a question like in the title
How to stop mounting the component in <router-view> until receive a data from server or how to get the data before the component is mounted to <router-view>
My files:
1st main.js
new Vue({
el: '#app',
router,
components: { Login, Start },
data: function(){
return{
info: null,
}
},
methods:{
bef: function(){
this.$http.get('xxx').then(function(response){
return response.body
});
}
},
beforeMount(){
this.info= this.bef()
}
})
2nd component file Comp.vue
export default{
name: 'start',
data(){
return{
}
},
beforeMount(){
console.log(this.$parent.info)
}
}
how to do it properly to get not null value, but response from the server?
Thank you in advance
resolved with:
checkLogged: function() {
return new Promise((resolve,reject) => {
this.$http.get('xxx').then(response => {
if (response.body == 1) {
resolve(true);
} else {
resolve(false);
}
}, response => {
reject('connection failure');
});
});
},
and in 2nd file:
this.$root.checkLogged().then((response) => {
if(response){
this.logged = true
}else{
router.push("/")
}
})

Add custom property to vuejs component

How do I set a custom property inside a vue component?
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
// This does not seem to work
this.item.customProperty = 'customProperty';
}
});
You can use Vue.set to add reactivity:
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
Vue.set(this.item, 'customProperty', 'customProperty');
}
});
It seems that you should use Object.assign:
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
// This does not seem to work
this.item = Object.assign(this.item, {customProperty:'customProperty'});
}
});

Categories