# 3.- Realizando cosas con Vue
# Mostrar datos
{
"frameworks": [
{
"framework": "Laravel",
"description": "description 1 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/php/"
},
{
"framework": "Django",
"description": "description 2 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/java/"
},
{
"framework": "NodeJS",
"description": "description 3 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/php/"
},
{
"framework": "Express",
"description": "description 4 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "https://romadesign.github.io/roma-fullstack/java/"
},
{
"framework": "Vue Js",
"description": "description 1 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/vuejs/"
},
{
"framework": "React Js",
"description": "description 2 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/reactjs/"
},
{
"framework": "JQuery",
"description": "description 3 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "/jquery/"
},
{
"framework": "Bootstrap",
"description": "description 4 ",
"img": "https://lenguajejs.com/javascript/logo.svg",
"url": "https://romadesign.github.io/roma-fullstack/java/"
}
]
}
En nuestro archivo vue importamos
import dataBackFront from "./json/BackFront.json";
# Utilizando JSON
export default {
data() {
return {
data: dataBackFront.frameworks,
};
},
mounted() {
this.$nextTick(function () {
// Código que se ejecutará solo después de
// haber renderizado la vista completa
const numberData = this.data;
numberData.sort(function () {
return Math.random() - 0.5;
});
});
},
};
Código para el html
<template>
<div class="container">
<div class="row">
<div class="cart" v-for="(front, f) in data.slice(0, 8)" :key="f">
<img :src="front.img" />
<h4>{{ front.framework }}</h4>
<span>{{ front.description }}</span>
<div class="link">
<a :href="front.url">Mirar</a>
</div>
</div>
</div>
</div>
</template>
# Mostrando datos aleatorios
//Solo mostramos 8 datos de todos los que tenemos en el array
data.slice(0, 8)
# Mostrando algunos datos
//Mostrando datos aleatorios
const numberData = this.data;
numberData.sort(function () {
return Math.random() - 0.5;
});
# Utilizando computed para mostrar algunos datos
import dataBackFront from "./json/BackFront.json";
export default {
data() {
return {
data: dataBackFront.frameworks,
};
},
methods: {},
mounted() {
const numberData = this.data;
numberData.sort(function () {
return Math.random() - 0.5;
});
},
computed: {
firstShoppingItems() {
return this.data
.map((x) => x)
.flat()
.slice(0, 8);
},
},
};
<div class="cart" v-for="(front, f) in firstShoppingItems" :key="f">
<img :src="front.img" />
<h4>{{ front.framework }}</h4>
<span>{{ front.description }}</span>
<div class="link">
<a :href="front.url">Mirar</a>
</div>
</div>
# Utilizando computed para mostrar algunos datos y hacer filter
Agregando un input para la busqueda
<input type="text" v-model="search" placeholder="Search" />
import dataBackFront from "./json/BackFront.json";
export default {
data() {
return {
data: dataBackFront.frameworks,
search: "",
};
},
methods: {},
mounted() {
const numberData = this.data;
numberData.sort(function () {
return Math.random() - 0.5;
});
},
computed: {
dataItems() {
return this.data
.filter((x) => {
return x.framework.toLowerCase().includes(this.search.toLowerCase());
})
.flat()
.slice(0, 4);
},
},
};
# Utilizando computed para mostrar datos aleatorios, filtrar y mostrar solo 4 dato de 100 en pantalla
computed: {
dataItems() {
return this.data
//mostrando aleatoriamente los datos
.sort(function () {
return Math.random() - 0.5;
})
//filtrando los datos para buscador
.filter((x) => {
return x.framework.toLowerCase().includes(this.search.toLowerCase());
})
.flat()
//Mostrando solo 4 datos de los 10 en el json
.slice(0, 4);
},
},
# Recorriendo json y verificando si existe
data() {
return {
data: dataBackFront.frameworks,
search: "",
searchNotFound: false,
length: 0,
};
},
methods: {
getLength: function () {
let busqueda = this.$refs.myInput.value;
console.log(busqueda);
let indice = this.data.findIndex((fr) => fr.framework === busqueda);
if (indice) {
const verdad = this.searchNotFound;
verdad === true;
}
console.log("El elemento buscado está en el índice ", indice);
},
},
# Buscando un item o objeto que esta en un array
<input
class="inputContent"
type="text"
v-model="search"
ref="myInput" <- caputara el dato
@keyup="getDataJsonExist" <- se coloca la función del methods
placeholder="Escribe tu framework o librería"
/>
data() {
return {
data: dataBackFront.frameworks,
search: "",
length: 0,
searchNotFound: false, // hide alert, si no encuentra dato
};
},
methods: {
getDataJsonExist() {
this.searchNotFound = true; //show alert, encontro dato
let busqueda = this.$refs.myInput.value.toLowerCase(); // capturamos datos ingresado del input y convirtiendo en minusculas
for (let fr of this.data) { //recorremos el array de datos
let searchFrameword = fr.framework.toLowerCase(); // guardamos los datos uno en uno en la variable nueva
if (searchFrameword.indexOf(busqueda) !== -1) { // indexOf - verifamos si existe el dato dentro del array con el dato ingresado en el input
this.searchNotFound = false; //hide alert, si encontro dato
}
}
},
},
// Otra opción es utilizar includes() <- Esto nos devolvera un "true" o "false"
# Realizando una llama a la api de github para mostrar los repositorios y utilizando FETCH para llamar y mostrar los datos con Vue
<script>
export default {
data() {
return {
repositorios: [],
};
},
created() {
fetch(`https://api.github.com/users/romadesign/repos`)
.then((response) => response.json())
.then((data) => (this.repositorios = data)); //Almacenando los datos en repositorios
}
};
</script>
Mostrando los datos por pantalla
<div v-for="(repo, r) in repositorios" :key="r">
<h4>{{ repo.name }}</h4>
<h4>{{ repo.ssh_url }}</h4>
</div>
# Realizando un evento para hacer click y enviar un dato para realizar un nuevo get a la Api de Github
Acá tenemos los lenguajes que se utilizaron para el proyecto al hacer click
<div class="content_button">
<!--Acá realizamos el click para llamar a la api y guardamos el argumento por name-->
<button @click="onClickLenguages(repo.name)">Lenguajes</button>
<a :href="repo.svn_url">Repositorio</a>
<a :href="repo.homepage">Mirar </a>
</div>
export default {
data() {
return {
repositorio: [],
repoLenguages: [],
};
},
created() {},
props: {},
methods: {
onClickLenguages(name) {
fetch(`https://api.github.com/repos/romadesign/${name}/languages`)
.then((response) => response.json())
.then((data) => {
console.log(JSON.stringify(Object.keys(data))); //Se tiene solo las claves para mostrar los datos en pantalla
this.repoLenguages = Object.keys(data); //guardamos los datos
});
},
},
watch: {},
computed: {},
};
</script>
Otros recursos: Mostrando algunos datos de todo un array (opens new window)
Capturando texto de los input (opens new window)
Recorriendo json y verificando si existe (opens new window)
Consumir API REST con VUE.js : Fetch y Axios. (opens new window)