Vue.js mixin - access data from mixin method - vue.js

I have the following Vue mixin in which I want to be able to have some data members and set values for them inside of a mixin method:
export const adComponentMixin = {
data() {
return {
ads1Code: "",
ads2Code: "",
ads3Code: "",
adsMobileCode: "",
};
},
mounted() {
this.ads1Code = document.getElementById("ads-div-hidden-1")?.innerHTML ?? "";
this.ads2Code = document.getElementById("ads-div-hidden-2")?.innerHTML ?? "";
this.ads3Code = document.getElementById("ads-div-hidden-3")?.innerHTML ?? "";
this.adsMobileCode =
document.getElementById("ads-div-hidden-mobile")?.innerHTML ?? "";
},
};
However, when I try to access this.ads1Code inside of the method, I get this error:
Property 'ads1Code' does not exist on type '{ data(): { ad1Code: string; ad2Code: string; ad3Code: string; adMobileCode: string; }; mounted(): void; }'.
How do I manipulate data inside of the mixin from a mixin method?

to implement mixins in other components, you need to do as following :
File - adComponentMixin.js
export default {
data() {
return {
ads1Code: "",
ads2Code: "",
ads3Code: "",
adsMobileCode: "",
};
},
mounted() {
this.ads1Code = document.getElementById("ads-div-hidden-1")?.innerHTML ?? "";
this.ads2Code = document.getElementById("ads-div-hidden-2")?.innerHTML ?? "";
this.ads3Code = document.getElementById("ads-div-hidden-3")?.innerHTML ?? "";
this.adsMobileCode =
document.getElementById("ads-div-hidden-mobile")?.innerHTML ?? "";
}
}
File - some-component.vue
<template>
<div>example</div>
</template>
<script>
import adComponentMixin from './adComponentMixin';
export default{
name:'some-component',
mixins:[adComponentMixin ]
}

Related

Pass data from vue file to js file in vuejs?

In file : Product.vue
beforeCreate() {
const productId = this.$route.params.id;
axios
.get("/localhost/api/product/" + productId)
.then((res) => {
console.log(res.data); // result : {name: 'Iphone', status: 3, quantity: 100, price: 800}
})
.catch((error) => {
console.log(error);
});
},
I have a file productData.js on the same level as Product.vue. Now I want to transfer data of res.data through productData.js, how to do? In other words in productData.js I want to get the result of res.data when I call the API. Thanks.
update :
let data = null;
function initData(apiRes) {
data = apiRes;
console.log(data); // Output: "Hi from server"
// Do something with Data
}
console.log(data) // I want to get data outside the initData function
export { initData };
Simplest way is:
Product.vue
<script>
import { initData } from "./productData.js";
export default {
name: "Product",
props: {
msg: String,
},
data() {
return {
apiRes: "",
};
},
mounted() {
// your api call
this.apiRes = "Hi from server";
initData(this.apiRes);
},
};
</script>
productData.js
let data = null;
function initData(apiRes) {
data = apiRes;
console.log(data); // Output: "Hi from server"
// Do something with Data
doSomethingWithData();
}
function doSomethingWithData() {
// Your app logic that depends on data
// Here data will have value from API
}
// Here data is always null
export { initData };

VueJS - function in import js file not getting triggered

We are building a web application using Vue JS and PHP, we are new to Vue JS. The server-side execution is fine, the API is able to fetch data as JSON. While trying out a static array display before making the API call, we find that the function in imported "app.js" is not getting called and the table displayed is empty. Please let us know what we might be doing wrong. Appreciate your help.
import Vue from 'vue';
export const MY_CONST = 'Vue.js';
export let memberList = new Vue({
el: '#members',
data: {
members: []
},
mounted: function () {
this.getAllMembers();
},
methods: {
getAllMembers: function () {
/*
axios.get("https://xxxxxx.com/services/api.php")
.then(function (response) {
memberList.members = response.data.members;
});
*/
memberList.members = [{ "empname": "Dinesh Dassss" },
{ "empname": "Kapil Koranne" }];
}
}
});
This is the Vue component. The members object is empty.
<script>
import * as mykey from './app.js'
export default {
name: 'Home',
props: {
msg: String
},
data() {
return {
message: `Hello ${mykey.MY_CONST}!`,
members: mykey.memberList.members
}
}
};
</script>
You can also use this reference for current instance reference:
getAllMembers: function () {
var me = this;
/*
axios.get("https://xxxxxx.com/services/api.php")
.then(function (response) {
// direct this not works here but we have
//saved this in another variable and scope of a var is there
me.members = response.data.members;
});
*/
// this reference works fine here.
this.members = [{ "empname": "Dinesh Dassss" },
{ "empname": "Kapil Koranne" }];
}

VueJS How to access Mounted() variables in Methods

I'm new in Vue and would like assistance on how to access and use variables created in Mounted() in my methods.
I have this code
Template
<select class="controls" #change="getCatval()">
Script
mounted() {
var allcards = this.$refs.allcards;
var mixer = mixitup(allcards);
},
methods: {
getCatval() {
var category = event.target.value;
// I want to access mixer here;
}
}
I can't find a solution anywhere besides this example where I could call a method x from mounted() and pass mixer to it then use it inside my getCatval()
Is there an easier way to access those variables?
I will first suggest you to stop using var, and use the latest, let and const to declare variable
You have to first declare a variable in data():
data(){
return {
allcards: "",
mixer: ""
}
}
and then in your mounted():
mounted() {
this.allcards = this.$refs.allcards;
this.mixer = mixitup(this.allcards);
},
methods: {
getCatval() {
let category = event.target.value;
this.mixer
}
}
like Ninth Autumn said : object returned by the data function and props of your components are defined as attributes of the component, like your methods defined in the method attribute of a component, it's in this so you can use it everywhere in your component !
Here an example:
data() {
return {
yourVar: 'hello',
};
},
mounted() { this.sayHello(); },
method: {
sayHello() { console.log(this.yourVar); },
},
Update
you cannot pass any value outside if it's in block scope - Either you need to get it from a common place or set any common value
As I can see, var mixer = mixitup(allcards); is in the end acting as a function which does some operation with allcards passed to it and then returns a value.
1 - Place it to different helper file if mixitup is totally independent and not using any vue props used by your component
In your helper.js
const mixitup = cards => {
// Do some operation with cards
let modifiedCards = 'Hey I get returned by your function'
return modifiedCards
}
export default {
mixitup
}
And then in your vue file just import it and use it is as a method.
In yourVue.vue
import Helpers from '...path../helpers'
const mixitup = Helpers.mixitup
export default {
name: 'YourVue',
data: ...,
computed: ...,
mounted() {
const mixer = mixitup(allcards)
},
methods: {
mixitup, // this will make it as `vue` method and accessible through
this
getCatval() {
var category = event.target.value;
this.mixitup(allcards)
}
}
}
2- Use it as mixins if your mixitup dependent to your vue and have access to vue properties
In your yourVueMixins.js:
export default {
methods: {
mixitup(cards) {
// Do some operation with cards
let modifiedCards = 'Hey I get returned by your function'
return modifiedCards
}
}
}
And import it in your vue file:
import YourVueMixins from '...mixins../YourVueMixins'
const mixitup = Helpers.mixitup
export default {
name: 'YourVue',
mixins: [YourVueMixins] // this will have that function as vue property
data: ...,
computed: ...,
mounted() {
const mixer = this.mixitup(allcards)
},
methods: {
getCatval() {
var category = event.target.value;
this.mixitup(allcards)
}
}
}

Vuejs 2 make a global function and pass param

In a component i am changing the title and description in mounted() but i want to make a global function so i can reuse the code below.
How can i achieve that?
window.document.title = 111;
document.head.querySelector('meta[name=description]').content = 222;
function getTitle(title){
return window.document.title = title;
}
I found the solution for this:
Vue.mixin({
methods: {
makeTitle: function (title) {
return window.document.title = title;
}
}
});
export default{
props: ['slug'],
data: function () {
return {
items: [],
}
},
mounted() {
this.makeTitle(this.slug);
},

Assign Vue-resource to a store

I am trying to store a resource in a store that can be shared between components according to the following documentation:
https://github.com/vuejs/vue-resource/blob/master/docs/http.md#response
http://vuejs.org/guide/application.html#State_Management
var App = Vue.extend({});
getcolleges = '/wp-json/wp/v2/schools-api?filter[posts_per_page]=9999';
var schoolFilter = Vue.extend({
template: '#school-filter-template',
data: function(){
return {
colleges: ''
}
},
ready: function() {
this.$http.get(getcolleges).then(function(colleges) {
this.$set('colleges', colleges.data);
})
},
});
However, when I try to create a store with the resource to use with other components, I get the following error: "The 'Data' option should be a function that returns a per-instance value in component definitions."
var App = Vue.extend({});
getcolleges = '/wp-json/wp/v2/schools-api?filter[posts_per_page]=9999';
var store = {
data: function(){
return {
colleges: ''
}
},
ready: function() {
vue.$http.get(getcolleges).then(function(colleges) {
vue.$set('colleges', colleges.data);
})
}
}
var schoolFilter = Vue.extend({
template: '#school-filter-template',
data: store
});