VUEJS

De wikiserver
La revisió el 12:05, 9 març 2020 per Jnoguera (Discussió | contribucions) (DIRECTIVA V-BIND)
Dreceres ràpides: navegació, cerca

v-text: para mostrar texto y que no parpadee

v-show: para mostrar u ocultar el elemento en función de su valor. v-show="true" es igual v-show="mensaje"

v-if y v-else:

V-TEXT

<body>

        <div id="el">
                <h1> {{mensaje}}</h1>    <!--podemos ver -->
        </div>
    </body>
    
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>  //CDN
    <script>
         Vue.config.devtools = true;    
         new Vue({
            el: '#el',   //hace referencia al elemento id= el
            data: {
                mensaje: "resultado"   //datos, hace referencia dentro de elemento #el {{mensaje}} 
            }
        })
    
    
    </script>


<body>
        <div id="el">
                <h1>Hola <span v-text="mensaje"> </span></h1>   <!--muestra "Hola" y luego en función del texto del input va rellenando-->
                <input type="text" class="text" v-model="mensaje">
        </div>
    </body>
    
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
    
        var variable = new Vue({
            el: '#el',
            data: {
                mensaje: "resultado"
            }
        })
    
     </script>


V-SHOW

v-show: para mostrar u ocultar el elemento en función de su valor. v-show="true" es igual v-show="mensaje"

<body>

    <div id="el">
            <h1 v-show="mensaje.length > 2">Ejemplo <span v-text="mensaje"> {{mensaje}}</span></h1>  <!--al recargar la pagina, se puede ver {{mensaje}} para evitar esto se usa la directiva v-text-->
            <input type="text" class="text" v-model="mensaje">
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>

    var variable = new Vue({
        el: '#el',
        data: {
            mensaje: "resultado"
        }
    })


</script>


<body>
        <div id="el">
                <h1 v-show="mensaje.length > 2">Hola <span v-text="mensaje"> </span></h1>   <!--si el mensaje es mayor que 2 muestra en caso contrario hace un display:none en css-->
                <input type="text" class="text" v-model="mensaje">
        </div>
    </body>
    
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
    
        var variable = new Vue({
            el: '#el',
            data: {
                mensaje: "resultado"
            }
        })
    
     </script>

V-IF

<body>
        <div id="el">
                <h1 v-if="mensaje.length > 2">Hola <span v-text="mensaje"> </span></h1>    <!--en vez de v-show podemos usar v-if-->
                <h1 v-else>otra</h1>
                <input type="text" class="text" v-model="mensaje">
        </div>
    </body>
    
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
    
        var variable = new Vue({
            el: '#el',
            data: {
                mensaje: "resultado"
            }
        })
    
     </script>


V-FOR

<body>
    <div id="el">
        <ul>
            <!-- <li v-text="profesores[0]"></li>-->
            <li v-for="profesor in profesores" v-text="profesor"></li>
        </ul>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#el',
        data: {
            profesores: [      //utilizamos un array con cadenas
                "Julio Noguera",
                "Albert Canela",
                "Alex Salinas"

            ]
        }
    })
</script>


Recorriendo Objetos

<body>
    <div id="el">
        <ul>
            <!-- <li v-text="profesores[0]"></li>-->
            <li v-for="profesor in profesores" v-text="profesor.nombre"></li>
        </ul>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#el',
        data: {    //utilizamos un array con objetos
            profesores: [   
                {nombre:"Julio Noguera"},
                {nombre: "Albert Canela"},
                {nombre: "Alex Salinas"}

            ]
        }
    })
</script>

Podemos especificar recorrer los objetos y mostrar o acceder a su contenido

<div id="el">
        <ul>
            <!-- <li v-text="profesores[0]"></li>-->
            <li v-for="profesor in profesores">
                <span v-text="profesor.nombre"></span>
                <small v-if="profesor.activo">-Activo</small>
                <small v-else>-NO está</small>
               
            </li>
        </ul>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#el',
        data: {
            profesores: [{
                    nombre: "Julio Noguera",
                    activo: true
                },
                {
                    nombre: "Albert Canela",
                    activo: true
                },
                {
                    nombre: "Alex Salinas",
                    activo: false
                }

            ]
        }
    })
</script>

//en Consola del navegador->
// variable.profesores[0].nombre ="Pepe"
// variable.profesores.push({nombre:"Joan Comas",activo:true})

EVENTOS y FUNCIONES

CLICK

Tenemos los datos mensajes y el array de profesores, también el método invertir que se ejecutará cuando se haga click en botón, también es interesante que para acceder a los datos se utiliza this.

<body>
    <div id="el">

        <input type="text" v-model="mensaje">
        <h1 v-text="mensaje"></h1>
        <!--  <button @click="mensaje=mensaje.split('').reverse('').join('')">BOTON</button> <!-- @click es abreviación de v-on:click -->

        <button @click="invertir">INVERTIR</button>

    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#el',
        data: {

            mensaje: " ",

            profesores: [{
                    nombre: "Julio Noguera",
                    activo: true
                },
                {
                    nombre: "Albert Canela",
                    activo: true
                },
                {
                    nombre: "Alex Salinas",
                    activo: false
                }

            ]
        },
        methods: {
            invertir: function () {
                this.mensaje = this.mensaje.split('').reverse('').join('');  //utilizamos this.mensaje para acceder a los datos 
            }
        }
    })
</script>

Mostrar lista asociando evento click

<body>
    <div class="container">
        <div id="elemento">
            <ul>
                <li v-for="profe in profesores">
                    <span v-text="profe.nombre"></span>
                    <span @click="profe.activo=false" v-if="profe.activo" class="glyphicon glyphicon-check"></span>
                    <span @click="profe.activo=true" v-else class="glyphicon glyphicon-unchecked"></span>

                </li>
            </ul>
            <pre>
                    {{$data}}
            </pre>


        </div>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#elemento',
        data: {

            profe: "",

            profesores: [{
                    nombre: "Julio Noguera",
                    activo: true
                },
                {
                    nombre: "Albert Canela",
                    activo: true
                },
                {
                    nombre: "Alex Salinas",
                    activo: false
                }

            ]

        }
    })
</script>


BOTÓN- AÑADIR LISTA

KEYUP

Eventos de teclado

<body>
    <div id="el">


        <ul>
            <!-- <li v-text="profesores[0]"></li>-->
            <li v-for="profesor in profesores">
                <span v-text="profesor.nombre"></span>
                <small v-if="profesor.activo">-Activo</small>
                <small v-else>-NO está</small>
            </li>

             <input v-on:keyup.13="anadir" type="text" v-model="profe" >   <!-- cuando apretamos el ENTER hace el evento (el 13 es enter en ascii)-->
             <!-- <input v-on:keyup.enter="anadir" type="text" v-model="profe" >  -->
           <!-- <input type="text" v-model="profe"> -->
           <!-- <button @click="anadir">+ añadir</button>-->
        </ul>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var variable = new Vue({
        el: '#el',
        data: {

            profe: "",

            profesores: [{
                    nombre: "Julio Noguera",
                    activo: true
                },
                {
                    nombre: "Albert Canela",
                    activo: true
                },
                {
                    nombre: "Alex Salinas",
                    activo: false
                }

            ]
        },
        methods: {
            anadir: function () {

                this.profesores.push({
                    nombre: this.profe,
                    activo: false
                });

            }
        }
    })
</script>


DIRECTIVA COMPUTED.

DIRECTIVA V-BIND

PARA ACTIVAR CLASES

<body>
  <div class="container">
      <div id="elemento">
          <ul>

<!--v-bind:class="['glyphicon',tarea.completo ? 'glyphicon-check': 'glyphicon-unchecked']"  //en el caso de querer añadir varias clases-->

              <li v-for="tarea in tareas"> 
                  <span v-text="tarea.nombre" @click="tarea.completo=!tarea.completo" ></span>
                  <input type="checkbox"  v-model="tarea.completo">
                 <span v-bind:class="{  
                               'glyphicon': true,   
                               'glyphicon-check':tarea.completo,
                               'glyphicon-unchecked': ! tarea.completo
                                }"></span>
              </li>
          </ul>
          <pre>
                  {{$data}}
               
          </pre>
      </div>
  </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
  var variable = new Vue({
      el: '#elemento',
      data: {

          tareas: [{
              nombre: "Estudiar",
              completo: true
          },
          {
              nombre: "Repasar",
              completo: true
          },
          {
              nombre: "Examinar",
              completo: false
          }

          ]

      }
  })
</script>
</script>


INCREMENTAR

Como se puede ver, se produce un incremento de voto modificando su atributo directamente.

<body>
    <div class="container">
        <h1>veamos</h1>
        <div>
            <ul>
              <li v-for="storie in stories"><button  @click="storie.votos++">Vote</button><pre v-text="storie.votos"></pre></li>
            </ul>
        </div>
        <pre>
{{$data | json}}
</pre>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '.container',
        data: {
            stories: [{
                    politico: "julio",
                    votos: 1
                },
                {
                    politico: "paco",
                    votos: 2
                },
                {
                    politico: "raúl",
                    votos: 3
                },
                {
                    politico: "jorge",
                    votos: 4
                },
            ]
        }        
    })


Ejercicio Incrementar edad y añadir nuevo profe

<div id="el"> 
        <div v-for="profesor in profesores" >
            <div v-text="profesor.nombre" ></div> <div v-text="profesor.edad"></div><span @click="incrementar(profesor)">+</span>
         </div>
        <input type="text" v-model="profesor" @click="anadir">
        <br>
        {{$data}}

    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    Vue.config.devtools = true
    var variable = new Vue({
        el: '#el',
        data: {

            profesor: " ",

            profesores: [{
                    nombre: "Julio Noguera",
                    edad: "0"
                },
                {
                    nombre: "Albert Canela",
                    edad: "1"
                },
                {
                    nombre: "Alex Salinas",
                    edad: "2"
                }

            ]
        },
        methods: {
            anadir: function(){
                this.profesores.push({nombre: this.profesor, edad: 0});
                console.log(this.profesor);
            },
            incrementar: function(profe){
                console.log(profe.edad++);
            }
        }
    });
    </script>

hacer calculadora

hacer CRUD

<body>
    <div id="el"> 
        <div v-for="tarea in tareas" >
            <div v-text="tarea" ></div> <span @click="eliminar(tarea)">X</span>
         </div>
        <input type="text" v-model="tarea"><span @click="anadir">+</span>
        <br>
        {{$data}}

    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    Vue.config.devtools = true
    var variable = new Vue({
        el: '#el',
        data: {

            tarea: "",

            tareas: []
        },
        methods: {
            anadir: function(){
                this.tareas.push(this.tarea);
                console.log(this.tareas);
            },
            eliminar: function(tarea){
                let x=this.tareas.indexOf(tarea);
                this.tareas.splice(x, 1);
            }
            
        }
    });
    </script>
</body>

</html>

https://www.youtube.com/watch?v=jfEEQVdbl54&list=PLPl81lqbj-4J-gfAERGDCdOQtVgRhSvIT&index=7&t=0s

Componentes

<body>
  <div id="aplicacion">
    <hola-mundo></hola-mundo>
  </div>
 
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<script>
  Vue.component('hola-mundo', {    //debe coincidir con el nombre del componente(etiqueta html)
    template: `<p>
                 Hola mundo
              </p>`
  });

  var app=new Vue({
    el: '#aplicacion'
  });
</script>
</body>
<body>
  <div id="aplicacion">
    <hola-mundo idioma="ingles"></hola-mundo>
    <hola-mundo idioma="castellano"></hola-mundo>
  </div>
 
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
  Vue.component('hola-mundo', {
    props: ['idioma'],
    template: `<div>
                  <p v-if="idioma=='castellano'">Hola mundo</p>
                  <p v-if="idioma=='ingles'">Hello world</p>
              </div>`
  })

  var app=new Vue({
    el: '#aplicacion'
  })
</script>

</body>

FILTRAR

<div id="aplicacion">
    <input type="range" v-model="minimo" min="0" max="50">  
    <div v-text="minimo"></div>


    <div v-for="dato in filtrar">
      <div v-text="dato.descripcion"></div>
    </div>

    <input type="search" v-model="campo">

    <div v-for="dato in busqueda">
      <div v-text="dato.descripcion"></div>
    </div>

  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script>
    Vue.config.devtools = true;
    var app = new Vue({
      el: '#aplicacion',
      data: {

        minimo: "5",

        campo: "",

        datos: [{
          codigo: 1,
          descripcion: 'papas',
          precio: 12.52
        }, {
          codigo: 2,
          descripcion: 'naranjas',
          precio: 21
        }, {
          codigo: 3,
          descripcion: 'peras',
          precio: 18.20
        }]
      },
      computed: {
        filtrar() {
          return this.datos.filter((dato) => dato.precio > this.minimo);
        },
        busqueda() {
          return this.datos.filter((dato) => dato.descripcion.includes(this.campo));
        }

      }
    })
  </script>