i am using vs code as ide.
this is the app code.
<template>
<div class="hello">
<!-- Select All records -->
<input type='button' #click='allRecords()' value='Select All users'>
<br><br>
<!-- Select record by ID -->
<input type='text' v-model='userid' placeholder="Enter Userid between 1 - 24">
<input type='button' #click='recordByID()' value='Select user by ID'>
<br><br>
<!-- List records -->
<table border='1' width='80%' style='border-collapse: collapse;'>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
<tr v-for='user in users'>
<td>{{ user.username }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</table>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWord',
data: {
users:"",
userid: 0
},
methods: {
allRecords: function () {
axios.get('api/ajaxfile.php')
.then(function (response) {
app.users = response.data;
})
.catch(function (error) {
console.log(error);
});
},
recordByID: function () {
if (this.userid > 0) {
axios.get('ajaxfile.php', {
params: {
userid: this.userid
}
})
.then(function (response) {
app.users = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
}
}
</script>
running the app code, chrome dev tools, like resposnse displays me the source code of the php file (which doesn't run).
The php file in another environment, using html including axios.js vue.js files as src (CDN) script works fine.
where am I wrong or how should I configure the vs code environment?
Because localhost:8080 runs no PHP server you must use a server which is running PHP, either on your local machine (e.g. MAMP) or on your public server. If the project resides under the folder my_project and the PHP file under the subfolder static, the proxyTable must look like:
proxyTable: {
'/static/dserver.php': {
target: 'http://localhost/my_project',
changeOrigin: true
}
which resolves in http://localhost/my_project/static/dserver.php .
Related
I'm building a component on my project, which is actually getting all the data and console logging it, but here's the problem: Inside my array of clients, i have some objects (address, documents, ...), and i can't manage to call them on my table.
My script:
<script>
export default {
data: () => ({
clients: [],
}),
methods: {
getClients() {
this.$api
.get("/api_v1/clientes", {
})
.then((response) => {
this.clients = response.data[0];
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
},
mounted() {
this.getClients();
},
};
</script>
My table (inside ):
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
{{ `${client.address.localidade} / ${client.address.uf}` }}
</td>
<td v-else>-</td>
<td>
<a :href="`/see-client/${client.id}`"
><i class="icon-magnifier"></i
></a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
My controller:
public function index(Request $request)
{
$data = [
'pag' => 'All clients',
'link' => '/'
];
return view('clients.index', $data);
}
The data:
Someone have a clue of a different approach i could have? I'm using Vue2. It's one of my first big projects, so previously sorry for any rookie mistake. Thanks for your time and help!
This line is only getting the first client:
this.clients = response.data[0];
response.data is your array of clients (from the looks of things). When you use .data[0], you're getting the first element of the array (i.e. the first client).
Then, this line is trying to loop over 1 client, not an array of clients.
<tr v-for="client in clients" v-bind:key="client.id">
Try changing
this.clients = response.data[0];
to
this.clients = response.data;
If that doesn't work (it looks like you've got a weird data structure), try this instead:
this.clients = response.data.data;
Or this (it's unclear to me how many nested data properties you have):
this.clients = response.data.data.data;
I just made a quick analysis about your code. I think you should polish it a little bit.
Let me start with a quick catch up:
Update yuor js section with:
<script>
export default {
// Please do use the function format instead of lambda expression, it's recommended in the vue2 docs.
data() {
return {
clients: [],
};
},
methods: {
// Change this to an async method, so you can have more control on your code.
async getClients() {
try {
/**
* Here, you should have to know, that your file `routes/api.php` hass all of the prefixed /api routes
* So you have a direct access to /api prefixed routes
* Additionally read a little bit about destructuring.
*/
const response = await this.$api.get("/api/clientes");
// Now, please notice that you have 2 data path names.
this.clients = response.data.data; // {or please follow the correct path to the array container of the clients}.
} catch (e) {
console.log("Check this error: ", e);
}
},
},
// Now, change your mounted to an async method
async mounted() {
// Trust me this is going to work perfectly.
await this.getClients();
},
};
</script>
Now, please, please change your api controller logic to a response()->json(...)
public function index(Request $request)
{
// Your retrieve logic...
return response()->json($data);
}
Finally if you have successfully configured everything abouve, your vue component should be able to retrieve the information correctly, and your tbody must work this way...
<tbody>
<tr v-for="client in clients" v-bind:key="client.id">
<td>{{ client.id }}</td>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td>{{ client.documents.cpf || client.documents.cnpj }}</td>
<td>{{ client.documents.celular }}</td>
<td>{{ client.status }}</td>
<td v-if="client.address">
<!-- You can replace what you have with: -->
{{ client.address.localidade }} / {{ client.address.uf }}
</td>
<td v-else>
-
</td>
<td>
<a :href="`/see-client/${client.id}`">
<i class="icon-magnifier"></i>
</a>
<i class="icon-check" style="color: green"></i>
<i class="icon-close" style="color: red"></i>
</td>
</tr>
</tbody>
I am trying to display data stored in a Firebase remote database in a Vue 3 webpage with a table however when I route to the display page I return the error. This is what my code looks like.
This is the HTML that displays the table:
<template>
<section v-if="!this.results.length">
No data to show
</section>
<section v-else>
<table class="table">
<thead>
<tr>
<th scope="col">View</th>
<th scope="col">Identification</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr v-for="res in results" :key="res.id">
<!-- <td><button class="btn btn-primary">View</button></td> -->
<td>{{res.idCard}}</td>
<td>{{res.name}}</td>
<td>{{res.surname}}</td>
<td>{{res.email}}</td>
<!-- <td><button class='btn btn-primary'>Update</button></td> -->
</tr>
</tbody>
</table>
</section>
</template>
And this is the Javascript. Here it is supposed to fetch the data from the firebase and push it into the results[] array.
<script>
export default {
data(){
return{
results: []
};
},
methods:{
async getData(){
console.log("Getting data");
try{
const response = await fetch("https://fir-example-56e32-default-rtdb.europe-west1.firebasedatabase.app/contact.json",{
method: 'GET'
}) //the below will parse the data thats part of the response if it is in json format; returns a promise
const responseData = await response.json();
if(!response.ok){
console.log("Something went wrong")
}
const results = [];
for (const id in responseData){
results.push({
id:id,
idCard: responseData[id].idCard,
name: responseData[id].name,
surname: responseData[id].surname,
email: responseData[id].email,
});
this.results = results;
}
}catch(error){
console.log(error);
}
},
},
//when component is fully initialised call method
mounted(){
this.getData();
}
}
</script>
the form in question
what it should look like
I have a probem to load data from database into my table created im vueJS. i have created my component table and my script in app.js, but in view i can see this error:
[Vue warn]: Property or method "datosUsuario" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Formularioactualizacion> at resources/js/components/datosUsuarios.vue
is problem to v-for that it not detect my array from script vue. i have checked my array for is empty, but not, he have data. Also i have a new route for load de data user and other for load the view and all it´s ok, but i can´t load de data into de table. I attached my actual code.
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('usuarios-component', require('./components/usuariosComponent.vue').default);
Vue.component('formularioactualizacion', require('./components/datosUsuarios.vue').default);
// inicio de VUE
const app = new Vue({
el: '#contenedorVue',
created: function(){
this.cargar();
},
data: {
datosUsuario: [],
},
methods: {
cargar: function(){
let url = '/getDatosPersonales';
axios.get(url).then((response) => {
this.datosUsuario = response.data;
}).catch((error) => console.error(error));
},
enviar(){
let url = '/actualizarDatos';
axios.post(url, {
id: this.id,
nombreUsuario: this.nombreUsuario,
email: this.email,
password: this.password,
direccion: this.direccion
}).then(function(response){
this.arrayTasks = response.data;
}).catch(function(error){
console.log(error);
})
}
}
});
Component
<template>
<div class="tabla-usuarios">
<table class="table table-hover table-striped">
<thead>
<th>ID</th>
<th>NOMBRE</th>
<th>EMAIL</th>
<th>DIRECCIÓN</th>
<th>CONTRASEÑA</th>
</thead>
<tbody>
<tr v-for="usuario in datosUsuario" :key="usuario.id">
<td>{{ usuario.id }}</td>
<td>{{ usuario.nombre }}</td>
<td>{{ usuario.email }}</td>
<td>{{ usuario.direccion }}</td>
<td>{{ usuario.password }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
datosUsuario: [],
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
console.log(this.datosUsuario);
})
.catch((error) => console.error(error));
},
},
};
</script>
my problem is in component in this v-for... i´m new in vueJS, i´m traying initiate in this frameworks.
Thanks so much for help
EDIT
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.
warn # app.js:38441
./node_modules/vue/dist/vue.common.dev.js.strats.data # app.js:39068
mergeField # app.js:39372
mergeOptions # app.js:39367
Vue.extend # app.js:42959
Vue.<computed> # app.js:43037
./resources/js/app.js # app.js:49878
__webpack_require__ # app.js:20
0 # app.js:50103
__webpack_require__ # app.js:20
(anonymous) # app.js:84
(anonymous) # app.js:87
app.js:38441 [Vue warn]: Property or method "datosUsuario" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Formularioactualizacion> at resources/js/components/datosUsuarios.vue
<Root>
here you Component is looking for datosUsuario variable inside that component that's why your getting that error to fix this
Component
<template>
<div class="tabla-usuarios">
<table class="table table-hover table-striped">
<thead>
<th>ID</th>
<th>NOMBRE</th>
<th>EMAIL</th>
<th>DIRECCIÓN</th>
<th>CONTRASEÑA</th>
</thead>
<tbody>
<tr v-for="usuario in datosUsuario" :key="usuario.id">
<td>{{ usuario.id }}</td>
<td>{{ usuario.nombre }}</td>
<td>{{ usuario.email }}</td>
<td>{{ usuario.direccion }}</td>
<td>{{ usuario.password }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
datosUsuario: [],
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
enviar() {
let url = "/actualizarDatos";
axios
.post(url, {
id: this.id,
nombreUsuario: this.nombreUsuario,
email: this.email,
password: this.password,
direccion: this.direccion,
})
.then(function (response) {
this.arrayTasks = response.data;
})
.catch(function (error) {
console.log(error);
});
},
},
};
</script>
and remove function form app.js
I want to display the list of record into webpage . I am using vuejs for front end development and mysql for backend .I created this applications by using LoopBack. I have some list of records inside the mysql database but the problem is when i run the web page , its does not display the records and when i want to insert new records , i am getting errors on this line ..
**(index):96 PUT http://localhost:3000/api/Account/ 400 (Bad Request)
storeAccount # (index):96
submit # VM346:3
invokeWithErrorHandling # vue.js:1863
invoker # vue.js:2188
original._wrapper # vue.js:7541**
When i clicked the index.js ,its showing error in this line
fetch(API, {...
Here is code for server.js file.
// Copyright IBM Corp. 2016. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
Here is my html code .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="AccountApp">
<h1>Account List</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Email Address</th>
<th>Created Date</th>
<th>Updated Date</th>
<td> </td>
</tr>
</thead>
<tbody>
<tr v-for="account in accounts">
<td #click="editAccount(account)" class="accountItem" title="Click to Edit">{{account.id}}</td>
<td>{{account.email}}</td>
<td>{{account.createdAt}}</td>
<td>{{account.lastModifiedAt}}</td>
<td #click="deleteAccount(account)" class="deleteAccount" title="Click to Delete">Delete</td>
</tr>
</tbody>
</table>
<form #submit.prevent="storeAccount">
<p>
<label for="email">Email</label>
<input type="text" id="email" v-model="account.email">
</p>
<p>
<label for="createdAt">Created At</label>
<input type="text" id="createdAt" v-model="account.createdAt">
</p>
<p>
<label for="lastModifiedAt">Last Modified At</label>
<input type="text" id="lastModifiedAt" v-model="account.lastModifiedAt">
</p>
<input type="reset" value="Clear" #click="reset">
<input type="submit" value="Save User 🐱">
</form>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<script>
const API = 'http://localhost:3000/api/Account/';
let AccountApp = new Vue({
el: '#AccountApp',
data: {
accounts: [],
account: {
id: '',
email: '',
createdAt: '',
lastModifiedAt: ''
}
},
created: function () {
this.getAccounts();
},
methods: {
getAccounts: function () {
fetch(API)
.then(res => res.json())
.then(res => this.account = res);
},
storeAccount: function () {
let method;
console.log('storeAccount', this.account);
// Handle new vs old
if (this.account.id === '') {
delete this.account.id;
method = 'POST';
} else {
method = 'PUT';
}
fetch(API, {
headers: {
'Content-Type': 'application/json'
},
method: method,
body: JSON.stringify(this.account)
})
.then(res => res.json())
.then(res => {
this.getAccounts();
this.reset();
});
},
deleteAccount: function (c) {
fetch(API + c.id, {
headers: {
'Content-Type': 'application/json'
},
method: 'DELETE'
})
.then(res => res.json())
.then(res => {
this.getAccounts();
});
// call reset cuz the cat could be 'active'
this.reset();
},
editAccount: function (c) {
/*
This line was bad as it made a reference, and as you typed, it updated
the list. A user may think they don't need to click save.
this.cat = c;
*/
this.account.id = c.id;
this.account.email = c.email;
this.account.createdAt = c.createdAt;
this.account.lastModifiedAt = c.lastModifiedAt;
},
reset: function () {
this.account.id = '';
this.account.email = '';
this.account.createdAt = '';
this.account.lastModifiedAt = '';
}
}
});
</script>
Here is the screenshot when i run the applications .
Here is the screenshot on Networks tab ..
I have a table with some to-do tasks and I want to be able to remove tasks through ajax but I do not know how to refresh my table after deleting.
I already am able to delete a task but I do not see the task removed until i refresh the page. I am sending some foo message to the template and I can see it but what I dont know is how to send the result of my query again and send a bunch of tasks to the template and show them in the table
this is my code
controller
class Delete(webapp2.RequestHandler):
def get(self):
string_id = self.request.get("task")[12:28]
task_key = ndb.Key('Task', int(string_id))
task_key.delete()
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
response_data = {'message' : 'foo'}
self.response.out.headers['Content-Type'] = 'text/json'
self.response.out.write(json.dumps(response_data))
return
class MainPage(webapp2.RequestHandler):
#login_required
def get(self):
session = Session(self.request)
user = User.get_by_id(session.email)
userkey=user.key
tasks=Task.query(Task.author==userkey)
template_values = {
'tasks': tasks
}
template = 'index.html'
render_template(self,template,template_values)
javascript
$(document).ready(function(){
$('.delete-button').click(function() {
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
});
return false;
});
})
function showData(data){
$('#prueba').html(data.message)
}
template
<table >
<thead>
<tr>
<th>Nombre</th>
<th>Descripcion</th>
<th>Fecha</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for task in tasks %}
<tr>
<td>{{ task.name }}</td>
<td>{{ task.description }}</td>
<td>{{ task.date|datetime }}</td>
<td>{{ task.status }}</td>
<td>
<form action="#" id="delete-form">
<input type="hidden" name="task" value="{{task.key}}">
<input type="submit" value="Eliminar" class="delete-button">
</form>
</td>
</tr>
{% endfor %}
<tbody>
</table>
<div id="prueba"></div>
Just refresh the page or after deleting in ajax make a Jquery function which will dynamically remove this object from your view. This are only two options you have ;)
For example:
$.ajax({
type: 'GET',
url: '/delete',
data: $('#delete-form').serialize(),
success: showData,
error: null
}, function() {
Your removing function
});
In your removing function you have to just simply find this object which you want to remove and remove it, for example:
$(#ObjectName).parents("li:first").remove();