So here's my code
var portal = new Vue({
el: "#AnnounceController",
data: {
ann: {
id: '',
content: ''
},
announces: [],
success: false,
edit: false
},
methods: {
fetchAnnounce: function () {
axios.get('/api/announces')
.then(function (response) {
this.announces = response.data;
console.log(this.announces);
})
.catch(function (error) {
console.log(error);
});
}
},
computed: {},
mounted: function () {
console.log('mounted')
this.fetchAnnounce()
}
I have a GET request via axios to a laravel based api, when I look at the response from axios I do see my data, when I try to assign that data to the 'announces' from data, it doesn't work. Vue-devtools shows my data 'announces' attribute as empty, and the log for this.announces shows me my data, somehow like the data attribute for the vue instance and the this.announces are different.
fetchAnnounce: function () {
axios.get('/api/announces')
.then(function (response) {
this.announces = response.data;
console.log(this.announces);
}.bind(this))
.catch(function (error) {
console.log(error);
});
}
Related
I have a Vue.js component in Laravel, it's loading with:
Vue.component('user-profile', require('./components/UserProfile.vue').default);
However, when I use this.$router.go() in it, I get the following error:
TypeError: Cannot read property '$router' of undefined
So, I've add this to my routes:
const routes = [
{
path: '/profile',
component: UserProfile
},
...
];
But then, I get:
Uncaught ReferenceError: UserProfile is not defined
So, I replaced:
Vue.component('user-profile', require('./components/UserProfile.vue').default);
by:
import UserProfile from './components/UserProfile.vue';
But I get this error:
Unknown custom element: - did you register the
component correctly?
How should I fix this issue to be able to use this.$router.go() in my component ?
=== EDIT ===
I'm using this.$router.go() here:
methods: {
async update () {
await axios.put(`/api/user/` + this.data.id, this.user)
.then(function (response) {
console.log(response);
this.$router.go()
})
.catch(function (error) {
console.log(error);
});
}
},
Either Use arrow function
methods: {
async update () {
await axios.put(`/api/user/` + this.data.id, this.user)
.then((response) => { // check here
console.log(response);
this.$router.go()
})
.catch((error) => {
console.log(error);
});
}
},
Or use var vm = this;
methods: {
async update () {
var vm = this;// check here
await axios.put(`/api/user/` + this.data.id, this.user)
.then(function (response) {
console.log(response);
vm.$router.go(); // check here
})
.catch(function (error) {
console.log(error);
});
}
},
Read about arrow function
**my rout file and when i type directly posts in URL it shows the posts but with created method in app.js it shows nothing **
Route::get('/posts', function () {
$posts_json = DB::table('posts')
->orderBy('posts.created_at','desc')->take(4)->get();return $posts_json;}
My app.js file
const app = new Vue({
el: '#app',
data: {
msg: 'make post',
content:'',
posts: [],
bUrl: 'http://localhost/pathikhome',
},
ready: function(){
this.created();
},
created(){
axios.get(this.bUrl +'/posts')
.then(response => {
console.log(response);
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
methods: {
addPost(){
axios.post(this.bUrl +'/addPost', {
content:this.content
})
if not success
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}});
ready is not supported anymore. That's Vue v1. Your new method is mounted. See https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram and https://v2.vuejs.org/v2/guide/migration.html#ready-replaced
Also data is a function that returns a data object, so if should look like this:
data: function() {
return {
msg: 'make post',
content: '',
posts: []
}
}
remove this.bUrl in the url of your axios:
created(){
axios.get('/posts')
.then(response => {
EDIT:
try to remove the ready function:
ready: function(){
this.created();
},
your data() should have a return inside:
data() {
return{
msg: 'make post',
content:'',
posts: [],
bUrl: 'http://localhost/pathikhome',
}
},
i am quite new in vuejs, so cant find out what am i doing wrong. This is my script part for a vue component:
<script>
export default {
name: 'product-main-info',
components: {
vueDropzone: vue2Dropzone
},
props: {
propId: String,
},
data() {
return {
images: {},
dropzoneOptions: {
url: '/uploadImg',
thumbnailWidth: 150,
maxFilesize: 2.0,
addRemoveLinks: true,
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg",
headers: { "X-CSRF-Token": document.head.querySelector('meta[name="csrf-token"]').content },
params: { id: this.propId },
init: function() {
var self = this;
self.on("success", function (file) {
this.$http.get('/getProductImages/' + this.propId)
.then(function(response) {
this.images = response.data;
});
});
}
}
}
},
methods: {
},
created() {
this.$http.get('/getProductImages/' + this.propId)
.then(function(response) {
console.log(response.data);
this.images = response.data;
});
}
}
</script>
I am trying to get new refreshed data after successful image upload, but all i get is:
app.js:16014 Uncaught TypeError: Cannot read property 'get' of undefined
All i need is to refresh my data, but i cant find out how to do this in a right way. Help if possible
constructor(){
super();
this.state = {
data: ''
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
this.setState({data: response }); // here i am getting error
console.log(this.state.data);
})
.catch(function (error) {
console.log(error);
});
In My react native app i am not able to setState the ajax response.. When i am trying to update the state here it throws error and execute catch function... I don't know why it happens can you please give me the quick suggestion
First of all, please read the difference between arrow functions and normal function declarations.
this.setState({}) will only work if you use arrow functions () => or you can do it the old fashion way by saving this inside a variable like so:
fetchData() {
const self = this;
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
self.setState({data: response }); // here i am getting error
console.log(self.state.data);
})
.catch(function (error) {
console.log(error);
});
}
I, however, prefer to use an arrow function instead as it's much simpler.
ex:
fetchData() {
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response => this.setState({data: response }) )
.catch(console.log);
}
P.S: You can also bind this using the .bind(this) method.
That's because you use the ES2015 syntax to create your function, which doesn't bind the context by default.
Use an arrow function instead :
.then((reponse) => {
console.log(response);
this.setState({data: response });
console.log(this.state.data);
}
I create SPA with VueJs and Laravel.
Homepage i get all posts via api laravel and axio responsive had data object.
But i can not update to posts property.
Error in chrome debug tool:
My code in Wellcome.vue
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
name: 'welcome',
layout: 'default',
metaInfo: { titleTemplate: 'Welcome | %s' },
computed: mapGetters({
authenticated: 'authCheck'
}),
data: () => ({
title: 'Demo Blog',
}),
props: {
posts: {
type: Object
}
},
created () {
axios.get('/api/posts')
.then(function (response) {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
You are using a regular function as a callback which means this reference changes. You need to use arrow function here . () => {}.
axios.get('/api/posts')
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
});
First of all you defined posts in your props property. You should not mutate a prop from child component. Props are One-Way-Data-Flow
you can inititialize posts in you data property as follows:
data(){
return{
posts: null
}
}
Then you can fetch data via your API and assign it to your posts in the data property
this in you then function does not point to the vue instance.
So its better you do it like this
created () {
var vm = this;
axios.get('/api/posts')
.then(function (response) {
vm.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
Or you an => function like this
created () {
axios.get('/api/posts')
.then( (response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}