Reputation:
I just switched from plain JavaScript to Typescript (or at least I'm trying to). Here is code that worked perfectly just before, minus the typing done so far:
<script lang="ts">
import axios from 'axios';
export default {
name: "Index",
data() {
return {
years: Array,
bgs: Array
}
},
methods: {
loadYears: function (): void {
let self = this;
axios.get('../letter/get/years').then(function (response) {
function pushYears(value: any) {
self.years.push(value);
}
response.data['years'].forEach(pushYears);
});
},
loadBg: function (): void {
let self = this;
axios.get('../bg/get/all').then(function (response) {
JSON.parse(response.data['bgs']).forEach(function (obj: any) {
self.bgs.push(obj);
})
});
}
},
beforeMount() {
this.loadYears();
this.loadBg();
}
}
</script>
now after switching to Typescript, self.years.push(value) and self.bgs.push(obj) are not working anymore, the corresponding errors says: "self.$data.years.push is not a function". Interestingly enough, in the beforeMount()-function I get an error saying that loadYears() and loadBg are not defined, but accessing the data()-objects works perfectly in this block via this.data().years or bgs. How can I access these properties inside my methods-block?
Upvotes: 2
Views: 3917
Reputation: 2761
you have two ways to type
yours data properties as bellow:
<script lang="ts">
import Vue from 'vue';
interface Model {
name: string
age: number
}
export default Vue.extend({
data () {
const foo: Model[] = [];
return {
foo,
bar: [] as Model[]
};
},
mounted () {
this.foo.push({
name: 'user', age: 22
});
this.bar.push({
name: 'guest', age: 20
});
},
});
</script>
Upvotes: 2