Axios is not defined in vue js applications - vue.js

I am developing shopping cart project in visual studio 2017. I am using vue js for front end development and mysql for backend . I added the axios script in my html code . When i run the application I following errors in google chrome console windows ..
Uncaught (in promise) ReferenceError: axios is not defined
at Promise.then.products (index.html:75)
at new Promise (<anonymous>)
at Vue.getAllProducts (index.html:74)
at index.html:130
index.html:110 Uncaught (in promise) ReferenceError: axios is not defined
at Promise.then.vendors (index.html:110)
at new Promise (<anonymous>)
at Vue.findAllVendors (index.html:109)
at index.html:131
Here is my html code .
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.map"></script>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="index.html">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html">Show All Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/AddProducts.html">Add Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.html"> cart</a>
</li>
</ul>
</nav>
<br />
<div class="container" id="app">
<select class="form-control" id="sel1" v-on:change="applyfilters($event.target.value)">
<option value="">Select Any value</option>
<option v-for="v in vendors" :value="v.id">{{ v.name }} </option>
<!-- <option value="v.id">{{v.name}}</option>-->
<!--<option value="2">MI</option>-->
</select>
<br />
<div class="row col-12" id="product-list">
<div class="col-4 card mx-2 p-2" v-for="product in products" style="margin-bottom: 20px">
<b>Product Name :</b>{{product.name}}
<div class="row">
<div class="col-4 m-3 p-3">
<b>Price :</b> {{product.price}}
</div>
<div class="col-4 m-3 p-3">
<b>Vendor :</b> {{product.vendor.name}}
</div>
<div class="col-6 m-2 p-3">
<button class="col btn btn-primary" v-on:click="addToCart(product.id)">Buy</button>
</div>
</div>
</div>
<br />
</div>
</div>
<script>
let app = new Vue({
el: "#app",
data: {
newTask: '',
id: 0,
url: '/todos',
status: false,
products: [],
vendors: []
},
methods: {
getAllProducts() {
new Promise((resolve) => {
axios.get('/api/products').then(function (response) {
resolve(response.data)
})
}).then((data) => {
this.products = data
// console.log(this.products)
})
},
addToCart(id) {
// console.log(id)
var obj = { productId: id };
// console.log(obj)
new Promise((resolve) => {
axios.post('/api/cart/', obj).then(function (response) {
resolve(response.data)
})
}).then((data) => {
// console.log(data)
console.log(data)
console.log(data.id)
if (!data.id) {
// console.log("fist login")
window.alert("Fist login ")
window.location = "signin.html";
}
else {
// console.log("successfully add to cart")
window.alert("product has been added to your cart")
}
})
},
findAllVendors() {
new Promise((resolve) => {
axios.get('/api/vendor').then(function (data) {
resolve(data.data)
// console.log(data.data)
})
}).then((data) => {
this.vendors = data
})
},
applyfilters(id) {
new Promise((resolve) => {
axios.get('/api/products/' + id).then(function (response) {
resolve(response.data)
})
}).then((data) => {
this.products = data
// console.log(this.products)
})
}
}
})
app.getAllProducts();
app.findAllVendors();</script>
</body>
</html>
Here is screen shot when i run the applications .

Did you try importing it? Maybe add this to your imports in head tag.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Related

calling a method on the root from a component, what is wrong with my code?

I have a component for my bootstrap modal. The modal has a button is labeled "Got It",which I am trying to call a method found on the root instance. It is not working--I cannot tell what I am missing. I have added a click handler and emit the click, but cannot trigger the clear function? Please advise what is wrong- thanks
Vue.component('modal', {
template: '#modal-template',
props:{
bgClass:{
type:String,
default:'default'
},
},
methods: {
clickHandler () {
this.$emit('click');
}
}
})
new Vue({
el: "#app",
data: function data() {
return{
showModalZ:false
}
},
methods: {
clear: function(){
alert("checkme");
}
}
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<script type="text/x-template" id="modal-template">
<transition name="modal">
<div class="vm-modal-mask">
<div class="vm-modal-wrapper">
<div class="vm-modal-container">
<div class="vm-modal-header">
<slot name="header">
default header
</slot>
</div>
<div :class="bgClass" class="vm-modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="vm-modal-footer">
<slot name="footer">
<button class="modal-default-button btn btn-primary" #click="clickHandler(),clear()">
Got It!
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
</script>
<div id="app">
<h5>hello <i style="font-size:20px;cursor:pointer;" aria-hidden="true" class="fa fa-info-circle" v-on:click="showModalZ=true"></i></h5>
<modal v-if="showModalZ" #close="showModalZ = false">
<h5 slot="header"><strong>input goes here</strong></h5> <hr>
<div>
test
</div>
</modal>
</div>
simply use this.$parent.$root.methodname()
e.g this.$parent.$root.clear();
Vue.component('modal', {
template: '#modal-template',
props: {
bgClass: {
type: String,
default: 'default'
},
},
methods: {
clickHandler() {
this.$parent.$root.clear();
}
}
})
new Vue({
el: "#app",
data: function data() {
return {
showModalZ: false
}
},
methods: {
clear: function () {
alert("checkme");
}
}
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<script type="text/x-template" id="modal-template">
<transition name="modal">
<div class="vm-modal-mask">
<div class="vm-modal-wrapper">
<div class="vm-modal-container">
<div class="vm-modal-header">
<slot name="header">
default header
</slot>
</div>
<div :class="bgClass" class="vm-modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="vm-modal-footer">
<slot name="footer">
<button class="modal-default-button btn btn-primary" #click="clickHandler()">
Got It!
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
</script>
<div id="app">
<h5>hello <i style="font-size:20px;cursor:pointer;" aria-hidden="true" class="fa fa-info-circle" v-on:click="showModalZ=true"></i></h5>
<modal v-if="showModalZ" #close="showModalZ = false">
<h5 slot="header"><strong>input goes here</strong></h5> <hr>
<div>
test
</div>
</modal>
</div>
You need to emit 'close' event from model component clickHandler function and capture it on parent with #close
Working example:
Vue.component('modal', {
template: '#modal-template',
props: {
bgClass: {
type: String,
default: 'default'
}
},
methods: {
clickHandler() {
this.$emit('close');
}
}
})
new Vue({
el: "#app",
data: function data() {
return {
showModalZ: false
}
},
methods: {
clear: function() {
alert("checkme");
}
}
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<script type="text/x-template" id="modal-template">
<transition name="modal">
<div class="vm-modal-mask">
<div class="vm-modal-wrapper">
<div class="vm-modal-container">
<div class="vm-modal-header">
<slot name="header">
default header
</slot>
</div>
<div :class="bgClass" class="vm-modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="vm-modal-footer">
<slot name="footer">
<button class="modal-default-button btn btn-primary" #click="clickHandler">
Got It!
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
</script>
<div id="app">
<h5>hello <i style="font-size:20px;cursor:pointer;" aria-hidden="true" class="fa fa-info-circle" v-on:click="showModalZ=true"></i></h5>
<modal v-if="showModalZ" #close="showModalZ = false">
<h5 slot="header"><strong>input goes here</strong></h5>
<hr>
<div>test</div>
</modal>
</div>

Local-Storage in Vue.JS

I am working on Vue.JS and I tried to use local-storage with it to save data. In my code, I can store and retrieve all data with local-storage except line-through effect. Here, I am trying to store actual boolean value of line-through effect in local-storage and want to retrieve that value on to-do list app.
<title>To Do List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<style>
.taskDone {
text-decoration: line-through;
}
</style>
</head>
<body>
<div id="todo-list" class="container">
<div class="container col-sm-8 col-sm-offset-2">
<h1 class="text-center"> <big><b> To Do List </b> </big></h1>
<h5 class="text-center"> <span v-show="itemsTodo.length"> ({{ itemsTodo.length }} pending) </span></h5>
<div class="col-md-8">
<button v-if="state === 'default'" class="btn btn-primary" #click="changeState('edit') ">Add Item</button>
<button v-else class="btn btn-info" #click="changeState('default')">Cancel</button>
</div>
<br>
<br>
<div v-if="state === 'edit'" >
<div class="col-sm-4">
<input class='form-control' v-model="newItem" type="text" placeholder="Type here" #keyup.enter="saveItem" >
</div>
<div class="col-sm-4">
<input class="form-control" v-model="newdate" type="date" type="text"/>
</div>
<div class="col-sm-4">
<button class='btn btn-primary btn-block' v-bind:disabled="newItem.length === 0"#click= "saveItem">Save Item</button>
</div>
</div>
<br>
<br>
<ul type="none" class="list-group">
<li class="list-group-item" v-for="(item,index,date) in items" :class="{taskDone : item.completed}" >
<h4>
<input type="checkbox" v-model="item.completed" #click="item.completed = !item.completed">
<button class="btn btn-primary " #click.stop="removeitems(index)">× </button>
<b><i> {{ item.label }} {{ item.date }} </i></b></h4>
</li>
</ul>
<h2 v-if="items.length === 0">Nice Job! Nothing in TO DO LIST</h2>
<div class="col-sm-4">
<button class="btn btn-warning btn-block" #click="clearcompleted"> Clear Completed</button>
</div>
<div class="col-sm-4">
<button class="btn btn-danger btn-block" #click="clearAll"> Clear All</button>
</div>
</div>
</div>
2. Vue.JS code
<script src="https://unpkg.com/vue" ></script>
<script>
var todolist = new Vue({
el: '#todo-list',
data : {
state : 'edit',
header: 'To Do List',
newItem: '',
newdate: '',
items: [
{
label:'coffee',
completed:false,
date:'2019-06-20' ,
},
{
label:'tea',
completed:false,
date:'2019-06-19' ,
},
{
label:'milk',
completed:false,
date:'2019-06-19' ,
},
]
},
computed:{
itemsDone(){
return this.items.filter(items => items.completed)
},
itemsTodo(){
return this.items.filter(items =>! items.completed)
},
},
methods:{
saveItem: function(){
if (this.newItem != ''){
this.items.push({
label:this.newItem,
completed: false,
date : this.newdate,
});
this.newItem = '';
this.newdate = '';
}},
changeState: function(newState){
this.state = newState;
this.newItem = '';
this.newdate = '';
},
removeitems(index){
this.items.splice(index,1);
},
clearcompleted (){
this.items = this.itemsTodo;
},
clearAll: function(){
this.items = [ ];
},
},
mounted(){
console.log('App Mounted!');
if (localStorage.getItem('items')) this.items = JSON.parse(localStorage.getItem('items'));
},
watch: {
items:{
handler(){
localStorage.setItem('items',JSON.stringify(this.items));
},
},
},
});
</script>
I expect correct boolean value of line-through effect to be stored in local-storage. So that, appropriate effect will show on browser.
You are just watching items. If you change something in a item (in your case completed) the handler will not be called and your change is not stored.
You could use a "deep" watcher but i suggest to call your save logic whenever you changed something.

why my code not working on ie11 after i use babel-polyfill?

I'm learning vue.js , everything works fine on chrome. but on ie11, it doesn't parsing the {{}} tag.
And after i use npm to install babel-polyfill,and used it as a tag on my page, the problem remains.
here are some of my code.
<script
type="text/javascript"
src="/node_modules/babel-polyfill/dist/polyfill.js"
></script>
<script type="text/javascript" src="/lib/vue/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/babel">
var vm = new Vue({
el: "#app",
data() {
return {
jobsData: null,
count: 0,
total: 0,
ls: 0,
le: 15
};
},
mounted() {
axios
.get("/activity/gqzq/AjaxGetList?ls=" + this.ls + "&le=" + this.le)
.then(response => {
console.log(response.data);
this.jobsData = response.data.data;
this.total = response.data.total;
this.count = response.data.count;
})
.catch(error => {
console.log(error);
});
}
});
</script>
<div class="result" v-for="job in jobsData">
<div class="job job-real" data-i="1" v-if="!job.has_next">
<div class="title">
<a
target="_blank"
:title="job.title"
:href="'/jobs/detail/' + job.id + '.html'"
>{{ job.title }}</a
><span class="dates hidden-xs"
>posttime:{{ job.posttime }} overtime:{{ job.overtime }}</span
>
</div>
<div class="info">
<div class="info_td com_name">
<a title="" target="_blank" href="/company/detail/9193.html">{{
job["company.name"]
}}</a>
</div>
<div class="info_td com_type hidden-sm hidden-xs">
{{ job["company.type"] }}
</div>
<div class="info_td com_location hidden-xs">
{{ job["company.area"] }}
</div>
<div class="info_td posttime hidden-xs">
{{ job.salary }}
</div>
</div>
</div>
</div>
vue suppose to parsing the contents in {{}},but it doesn't.
so how to fix this and what cause this problem?

How to fetch model value to api controller from ajax call

I am trying to add User Type details to database. When Passing through ajax to Web API ... model value is passing as null ... I need Model value to be passed as Parameter .. Can an one Help me on this
#model ConstructionModels.UserTypeModel
#using Newtonsoft.Json
#{
// Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>UserTypeModel</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.User_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.User_Type, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" id="btnSave" class="btn btn-default" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
var baseUrl= '#System.Configuration.ConfigurationManager.AppSettings["ApiUrl"]';
$("#btnSave").click(function () {
var data1 = #Html.Raw(JsonConvert.SerializeObject(this.Model));
console.log(data1);
$.ajax({
url: baseUrl + 'Usertype/Save',
type: 'post',
data: data1,
dataType: 'json',
success: function () {
alert("Saved");
},
error: function (error) {
alert("Error While Saving");
}
})
})
</script>

wechat platform can't load vue-resource or axios code

I developed a website for the WeChat Platform . The fronted website runs well on my own iphone. But these website won't work on others' phone, or the WeChat Windows version. I found if I comment out the code which related with the vue-resource or axios, the whole page worked fine. If not, the whole js file will not work.
The html code as below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,user- scalable=no" />
<title>Kindle Binding</title>
<!-- Compiled and minified CSS -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<!-- <script
src="https://unpkg.com/vue-resource#1.1.2/dist/vue-resource.min.js"> </script> -->
</head>
<style>
body {<!--
min-height: 2000px; -->
width: 100%;
height: 100%;
overflow-x: hidden;
}
#register_form {
margin-top: 20px;
}
</style>
<body>
<div id="register">
<div class="navbar-fixed">
<nav>
<div class="nav-wrapper black">
<a href="#" class="brand-logo" style="margin-left: 20px">Kindle
Pocket</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>register</li>
<li>login</li>
</ul>
</div>
</nav>
</div>
<div class="container">
<!-- register form start -->
<div id="register_form" class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i> <input
id="icon_prefix" type="text" class="validate"
v-model="newUserInfo.userName" /> <label for="icon_prefix">Username</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">phone</i> <input
id="icon_telephone" type="tel" class="validate"
v-model="newUserInfo.phone"> <label for="icon_telephone">Phone</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">email</i> <input id="icon_email"
type="email" class="validate" v-model="newUserInfo.email">
<label for="icon_email">Personal Email</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">lock</i> <input
id="icon_password" type="password" class="validate"
v-model="newUserInfo.emailPwd"> <label
for="icon_password">Personal Email Passcode</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">email</i> <input
id="icon_kindle_email" type="email" class="validate"
v-model="newUserInfo.kindleEmail"> <label
for="icon_kindle_email">Kindle Email</label>
</div>
</div>
<button type="button" style="float: right; margin-right: 20px"
class="btn waves-effect waves-light black" #click="register">
<font color="white">register</font>
</button>
<button type="button" style="float: right; margin-right: 20px"
class="btn waves-effect waves-light black" #click="test">
<font color="white">test</font>
</button>
</form>
</div>
</div>
</div>
</body>
<script src="https://unpkg.com/vue#2.1.10/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="/js/vue/register.js"></script>
<script
src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"> </script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script>
</html>
The js file as below:
/**
*
*/
var app = new Vue({
el: "#register",
data: {
registerUrl: "/KindlePocket/bindingData",
registerFlag: false,
newUserInfo: {
userName:'',
phone:'',
email:'',
emailPwd:'',
kindleEmail:''
}
},
methods: {
register: function() {
alert("entered the register function!")
if(this.newUserInfo.userName.trim() == ''
|| this.newUserInfo.phone.trim() == ''
|| this.newUserInfo.email.trim() == ''
|| this.newUserInfo.emailPwd.trim() == ''
|| this.newUserInfo.kindleEmail.trim() == '') {
alert("information uncompleted!");
return ;
} else {
alert("ready to register");
axios.post(this.registerUrl, this.newUserInfo,{
transformRequest: [function (data) {
// Do whatever you want to transform the data
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
alert("register success");
})
.catch(function (error) {
alert("register failed");
});
}
// vue-resource
/*this.$http.post(this.registerUrl, this.newUserInfo, { emulateJSON: true })
.then((response) => {
console.log(response.data);
if(response.data.isBinded == 1) {
this.registerFlag = true;
alert("register success!");
}
})*/
},
test: function() {
alert('test function invoked!');
}
},
created: function() {
alert('created function invoked!');
}
})
On my own iphone, when I click the test or register button , the js code runs well and the request send to the backend successfully, But on other phone , even the test button won't work. If I comment out the else block in the register function , all the devices runs well. When I replace axios with vue-resource, the same situation appeared. I don't know why.