[英]Laravel Vue Axios is not defined
我在laravel應用中使用vuetify框架構建了一個簡單表單。 bootstrap.js已經包含axios客戶端,但是提交時仍然出現錯誤,未定義axios:
[Vue警告]:事件處理程序中的“單擊”錯誤:“ ReferenceError:未定義axios”
這是新的laravel安裝隨附的Default bootstrap.js文件,我剛剛刪除了jquery:
window._ = require('lodash');
window.Popper = require('popper.js').default;
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
這就是我的app.js文件的樣子:
import bootstrap from 'bootstrap';
import 'material-design-icons-iconfont/dist/material-design-icons.css' // Ensure you are using css-loader
import Vue from 'vue';
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css';
Vue.use(Vuetify);
Vue.component('form-component', require('./components/FormComponent.vue'));
const app = new Vue({
el: '#app',
data: {
loading: true
},
});
FormComponent看起來像這樣,基本上我正在嘗試使用axios發布數據:
<template>
<v-container grid-list-xl>
<v-flex>
<v-text-field
v-model="name"
:error-messages="nameErrors"
:counter="10"
label="Name"
required
@input="$v.name.$touch()"
@blur="$v.name.$touch()"
></v-text-field>
</v-flex>
<v-flex>
<v-btn @click="submit">submit</v-btn>
<v-btn @click="clear">clear</v-btn>
</v-flex>
</v-container>
</template>
<script>
import { validationMixin } from 'vuelidate'
import { required, maxLength, email } from 'vuelidate/lib/validators'
export default {
mixins: [validationMixin],
validations: {
name: { required, maxLength: maxLength(20) }
},
data() {
return {
reactive: false,
name: '',
}
},
computed: {
nameErrors () {
const errors = [];
if (!this.$v.name.$dirty) {
return errors;
}
!this.$v.name.maxLength && errors.push('Name must be at most 10 characters long');
!this.$v.name.required && errors.push('Name is required.');
return errors;
},
},
methods: {
submit () {
this.$v.$touch();
axios.post('event/store', {
'name': this.name,
})
.then((response) => {
console.log("success");
})
.catch((error) => {
console.log("error");
})
},
clear () {
this.$v.$reset();
this.name = '';
}
}
}
</script>
我正在加載axios,所以我不知道為什么會出現該錯誤。
如果您不想在使用它的每個組件中導入它,可以將其添加到Vue原型中:
window.axios = require('axios');
//... configure axios...
Vue.prototype.$http = window.axios;
然后,您可以在任何組件中使用
this.$http.post('event/store', {
'name': this.name,
})
在組件中導入axios:
<script>
import axios from 'axios'
import { validationMixin } from 'vuelidate'
...
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.