I have a component with empty data array
data: () => ({
selectedResource : [],
}),
but when i try to add some item to this array i got an error
selectResource(resource){
console.log(this.selectedResource);
this.selectedResource.append(resource)
}
this.selectedResource.append is not a function
Using this should work
data() {
return {
selectedResource: [],
}
},
You can use $set for add item to array:
this.$set(yourArray, 'yourIndex', 'YourValue')
Related
i call for the api to fetch data, i test it with postman and laravel send it as an array correctly, but vue turn my array into [ob: Observer] and i cant extract my array from it thanks to #Stockafisso it has been solved but
Edit: now my problem is, programming_languages array is only accesible inside getLanguages() method not anywhere else
data(){
return{
answer: '',
maxWrong: '',
programming_languages : []
}
},
methods:{
getLanguages(){
axios.get('/api/toController').then((response)=> {
this.programming_languages = JSON.parse(JSON.stringify(response.data)); //works fine
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name; //works fine
this.maxWrong = this.answer.length;// works fine here, i dont want to initiaize answer variable in this method
});
},
randWord(){
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;// it is not working here
//Error in created hook: "TypeError: Cannot read property 'name' of undefined"
this.maxWrong = this.answer.length;// doesn't work here
}
},
created(){
this.getLanguages();
this.randWord();
}
what can i do?
thank you
most probable the error(s) is here:
this.programming_languages.push(JSON.parse(JSON.stringify(response.data)));
you are inserting the Laravel returned array inside the declared programming_languages, while you should override or concat it.
To explain better, a little example:
consider this:
let arr1 = [];
let arr2 = [1,2,3];
if you do arr1.push(arr2) your arr1 will be [[1,2,3]] while you want it to be [1,2,3].
Going back to your problem, to fix it you have two ways:
a)
.then((response)=> {
this.programming_languages = JSON.parse(JSON.stringify(response.data));
b)
.then((response)=> {
let swapArray = [...this.programming_languages];
this.programming_languages = swapArray.concat(JSON.parse(JSON.stringify(response.data)));
If this does not fix the error,
it could be the problem is in the array returned from Laravel. If it has not numeric or not sorted keys, JS will "fill" the missing spaces with Ob. Observer to try to keep the keys.
thank you all, finally i managed to solve it
first i extract array from vue's [ob: Observer]
this.programming_languages = JSON.parse(JSON.stringify(response.data));
special thanks to #stockafisso
and second was that i couldn't get this programming_languages array out of axios method, that happens due to nature of asynchronous call, see this informative link
How do I return the response from an asynchronous call?
i managed to solve it this way, async and await
methods: {
async getPosts(){
await axios.get('/api/hangman').then(response => {
this.programming_languages = JSON.parse(JSON.stringify(response.data));
}).catch(error => console.log(error));
},
randWord(){
this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;
this.maxWrong = this.answer.length;
},
},
created(){
this.getPosts().then(() => this.randWord());
}
I've been struggling a lot lately on how to set the initial value in local data property. I'm using Laravel with Vue.js
I have this code below in my component
props: {
user: '',
dates: {}
},
data() {
return {
bloodTypes: {},
bloodComponents: {},
data: {
order_date: this.dates.order_date,
order_details: []
},
}
},
I'm trying to get the value of the props 'dates' into the local variable.
order_date: this.dates.order_date
return undefined. Although you can see in the picture below that the props have been initialized.
I want to know how to get the props value into my local data
variables.
A little late to the party but I thought I would share my workaround when working with async data:
// in the parent component
<template>
<child :foo="bar" v-if="bar" />
</template>
Then you can safely follow the guide's recommended ways to initialize data value with props as so:
props: ['initialCounter'],
data: function () {
return {
counter: this.initialCounter
}
}
Happy coding!
try this:
watch: {
dates: {
handler(val){
this.data.order_date = val.order_date;
},
deep: true
}
}
I finally solved this with, I have changed some variable name so that I won't be confused. It seems that you need to put props under watch in order to manipulate it.
props: [ 'user','blood_components', 'blood_types', 'current_date'],
data() {
return {
list: {
order_date: '',
}
}
},
watch:{
current_date: function() {
let self = this
self.list.order_date = this.current_date
}
},
How about using computed instead?
props: [
'user',
'dates'
],
data() {
return {
bloodTypes: {},
bloodComponents: {}
}
},
computed: {
data: function() {
return {
order_date: this.dates.order_date,
order_details: [] <= should be changed to something dynamically changed object
}
}
}
The problem is your props are not declared correctly.
props: {
user: '', // <-- DON'T DO THIS
dates: {} // <-- DON'T DO THIS
}
When using the object syntax for props, each key is the prop name, and the value is either a data type (e.g., String, Number, etc.):
props: {
user: String,
dates: Object
}
...or an object initializer (which allows you to specify data type and default value) like this:
props: {
user: {
type: String,
default: ''
},
dates: {
type: Object,
default: () => ({})
}
},
demo
Assign the values in the created or mounted hook.
Example: https://github.com/jserra91/vuejs_wrapper_elements_and_unit_tests/blob/master/src/components/ae/components/ea-select/EaSelect.vue
I'm trying to get values using axios and on my browser returns [[PromisseValue]] undefined. Follow my code. Please, help-me... thanks
This is my data to get
<script>
export default {
props: ['endpoint'],
data () {
return {
response: {
table: '',
displayable: [],
records: []
}
}
},
methods: {
getRecords () {
return axios.get(`${this.endpoint}`).then((response) => {
console.log(response.data.data.table)
})
}
},
mounted () {
this.getRecords()
}
}
It will return promise because AXIOS is a promise function that you are trying to return.
axios.get(`${this.endpoint}`).then((response) => {
this.response.table = response.data.data.table
})
after axios call you need save it into your state or data the response then use it wherever you want.
I may be wrong in my understanding of props but I can't seem to be able to pass a prop to a component and then use the value in a method?
So far I am able to get data from a fixed API and output everything from the vue component, now I would like the api source to be dependent on the variable passed to the component.
My blade template:
<projectstatuses :userslug="this-user" :projectslug="this-project"></projectstatuses>
Then in my Vue Component:
export default {
props: {
userslug: {
type: String,
default: "other-user",
},
projectslug: {
type: String,
default: "other-project",
}
},
data() {
return {
statuses : [],
}
},
created(){
this.getStatuses();
},
methods : {
getStatuses(){
console.log(this.userslug);
console.log(this.projectslug);
axios.get('/api/' + this.userslug + '/' + this.projectslug)
.then((response) => {
let statuses = response.data;
this.statuses = statuses.statuses;
console.log(response.data.statuses);
})
.catch(
(response) => {
console.log('error');
console.log(response.data);
}
);
}
}
}
In the console I get the default values, if I remove the default values I get undefined. I have tried removing the api method and simply console logging the values but I still get undefined. Is what I'm trying to do possible or have I completely misunderstood how props work?
You are trying to bind this-user and this-project as a properties not as values ,
So you will need to define them in the data object in the parent,
but if you want to pass this-user and this-project just as value remove the : try that:
<projectstatuses userslug="this-user" projectslug="this-project"></projectstatuses>
Dynamic-Props
Don't add : in your template:
<projectstatuses userslug="this-user" projectslug="this-project"></projectstatuses>
Vue will expect there's data bound to this-user.
Problem: Although from the Vue DevTools I am passing the prop correctly and the router-view component has access to the data that it needs and in the correct format, whenever I try to access any of the data properties from within the template I get Uncaught TypeError: Cannot read property 'name' of null. It's really confusing because from the DevTools everything is a valid object and the properties are not null.
App.js
const game = new Vue({
el: '#game',
data: function() {
return {
meta: null,
empire: null,
planets: null
};
},
created: () => {
axios.get('/api/game').then(function (response) {
game.meta = response.data.meta;
game.empire = response.data.empire;
game.planets = response.data.planets;
});
},
router // router is in separate file but nothing special
});
main.blade.php
<router-view :meta="meta" :empire="empire" :planets="planets"></router-view>
script section of my Component.vue file
export default {
data: function() {
return {
}
},
props: {
meta: {
type: Object
},
empire: {
type: Object
},
planets: {
type: Array
}
}
}
Any ideas? Thanks in advance.
Because of your data is async loading so when my Component.vue renders your data in parent component may not be there. So you need to check if your data is loaded. You can try this code:
{{ meta != null && meta.name }}
PS: Your created hook should be:
created() {
axios.get('/api/game').then((response) => {
this.game.meta = response.data.meta;
this.game.empire = response.data.empire;
this.game.planets = response.data.planets;
});
},
router-view is a component from view-router which can help render named views. You can not pass empire and planets to it as those are props of your component.
You have to have following kind of code to pass empire and planets to your component:
<my-component :meta="meta" :empire="empire" :planets="planets"></my-component>
You can see more details around this here.