Vue: propiedades calculadas y oyentes

Tabla de contenido

1. Propiedades calculadas

1. Uso básico

2. Uso complicado

3. getter y setter

4. Comparación de propiedades y métodos.

Dos, el oyente

1. Uso del reloj


1. Propiedades calculadas

1. Uso básico

​ Ahora hay variables apellido y nombre, para obtener el nombre completo.

   <div id="app">

        <h2>您的firstname:{
   
   {firstName}}</h2>
        <h2>您的lastname:{
   
   {lastName}}</h2>
        
        <h2>您的fullname是从计算属性中得到:{
   
   {fullName}}</h2>

        <h2>您的fullname是从方法中得到:{
   
   {getFullName()}}</h2>

    </div>
    <script>
        Vue.config.productionTip = false;  //阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el: '#app',
            data(){
                return{
                    firstName:'zhang',
                    lastName:'san'
                }
            },
            methods: {
                getFullName(){
                    return this.firstName + this.lastName
                }
            },
            computed:{//计算属性 一定要有一个返回值 在页面中渲染时是不需要加小括号的
                fullName(){
                    return this.firstName + this.lastName
                }
            }
        })
    </script>

  Empalme usando la sintaxis Mastache<h2>{ {firstName}}{ {lastName}}</h2>

  Cómo utilizar los métodos<h2>{ {getFullName()}}</h2>

  Usando la propiedad calculada<h2>{ {fullName}}</h2>

En el ejemplo, el atributo calculado tiene el mismo aspecto que el método, excepto que las llamadas al método deben usar (), mientras que los atributos calculados no. El nombre del método es generalmente un verbo y el nombre del atributo calculado es un sustantivo. , pero este es sólo un uso básico. 

2. Uso complicado

   Ahora hay una matriz de libros de datos, que contiene muchos objetos de libro, la estructura de datos es la siguiente:

libros:[ 
          {id:110,nombre:"JavaScript de entrada a entrada",precio:119}, 
          {id:111,nombre:"Java de entrada a abandono",precio:80}, 
          {id:112,nombre: "El arte de codificar",precio:99}, 
          {id:113,nombre:"Enciclopedia de códigos",precio:150}, 
        ]

    ​ Se requiere calcular el precio total de todos los libros totalPrice.

<div id="app">
			<h2>您的总价:{
   
   {totalPrice}}</h2>
		</div>
		<script>
			const vm = new Vue({
				el: '#app',
				data() {
					return {
						books: [{
								id: 110,
								name: "JavaScript从入门到入土",
								price: 119
							},
							{
								id: 111,
								name: "Java从入门到放弃",
								price: 80
							},
							{
								id: 112,
								name: "编码艺术",
								price: 99
							},
							{
								id: 113,
								name: "代码大全",
								price: 150
							},
						]
					}
				},
				computed: {
					/* totalPrice() {
						let total = 0
						for (let i = 0; i < this.books.length; i++) {
                              total += this.books[i].price
						}
						return total
					} */
					
					/* totalPrice() {
						let total = 0
						for (let index in this.books) {
							total += this.books[index].price
						}
						return total
					} */
					
					/* totalPrice() {
						let total = 0;
						for(let item of this.books){
							total += item.price
						}
						return total
					} */
					
					/* totalPrice() {
						let total = 0;
						this.books.forEach(item=>{
							total += item.price
						})
						return total
					} */
					
					/* map */
					/* totalPrice() {
						let total = 0;
						this.books.map(item=>{
							total += item.price
						})
						return total
					} */
					
					/* filter */
					/* totalPrice() {
						let total = 0;
						this.books.filter(item=>{
							total += item.price
						})
						return total
					} */
					
					/* reduce */
					/* totalPrice() {
						return this.books.reduce((total,item)=>{
							 return total + item.price 
						},0)
					} */
					
					/* totalPrice() {
						return this.books.reduce((total,item)=>total + item.price,0)
					} */
					
					/* some */
					totalPrice() {
						let total = 0;
						this.books.some(item=>{
							total += item.price
						})
						return total
					}
					
				}
			})
		</script>

Obtenga la acumulación de precios de cada objeto de libro. Cuando el precio de uno de los libros cambie, el precio total cambiará en consecuencia.

3. getter y setter

En la propiedad calculada, en realidad hay dos métodos, definidor y captador.

Pero las propiedades calculadas generalmente no tienen un método establecido, las propiedades de solo lectura solo tienen un método get, pero en lo anterior newValue es un valor nuevo, también puede usar el método set para establecer el valor, pero generalmente no.

       <div id="app">
			<input type="text" v-model="firstName"/><br>
			<input type="text" v-model="lastName"/><br>
			<input type="text" v-model="fullName"/>
			<!-- v-model实现数据的双向绑定 -->
			<!-- 2.双向绑定(v-model):数据不仅能从data流向页面,还可以从页面流向data。
						备注:
								1.双向绑定一般都应用在表单类元素上(如:input、select等)
								2.v-model:value 可以简写为 v-model,因为v-model默认收集的就 
                                   是value值。 -->
		</div>
		<script>
			const vm = new Vue({
				el: '#app',
				data() {
					return {
						firstName: 'zhang',
						lastName: 'san'
					}
				},
				computed: { //计算属性 一定要有一个返回值 在页面中渲染时是不需要加小括号的
					/* fullName(){
						return this.firstName + this.lastName
					} */

					 fullName: {
						get: function() {
							return this.firstName +','+ this.lastName
						},
						set:function(val){
							var list = val.split(',')
							console.log(list);
							this.firstName = list[0]
							this.lastName = list[1]
						}
					} 
				}
			})
		</script>

 

 De esta manera, podemos cambiar el valor de propiedad asociado con la propiedad calculada mientras cambiamos el valor de la propiedad calculada.

4. Comparación de propiedades y métodos.

       <div id="app">
			<h2>您的fullname是从计算属性中得到:{
   
   {fullName}}</h2>
			<h2>您的fullname是从计算属性中得到:{
   
   {fullName}}</h2>
			<h2>您的fullname是从计算属性中得到:{
   
   {fullName}}</h2>
			<h2>您的fullname是从计算属性中得到:{
   
   {fullName}}</h2>
			
			<h2>您的fullname是从方法中得到:{
   
   {getFullName()}}</h2>
			<h2>您的fullname是从方法中得到:{
   
   {getFullName()}}</h2>
			<h2>您的fullname是从方法中得到:{
   
   {getFullName()}}</h2>
			<h2>您的fullname是从方法中得到:{
   
   {getFullName()}}</h2>
		</div>
		<script>
			const vm = new Vue({
				el:'#app',
				data(){
					return {
						firstName:'zhang',
						lastName:'san'
					}
				},
				methods:{
					getFullName(){
						console.log('这里调用了方法getFullName');
						return this.firstName + this.lastName
					}
				},
				computed:{//计算属性 一定要有一个返回值 在页面中渲染时是不需要加小括号的
					fullName(){
						console.log('这里调用了计算属性fullName');
						return this.firstName + this.lastName
					}
				}
			})
			
			/* 总结:计算属性的性能是优于方法的 因为计算属性是具有缓存特性的 */
		</script>

Se puede ver que el atributo calculado tiene un caché. En this.firstName + " " + this.lastNameel caso del mismo atributo, los métodos se llaman cuatro veces, mientras que el atributo calculado se llama solo una vez. El rendimiento de los atributos calculados es obviamente mejor que el de los métodos. Y en el caso de cambiar el nombre, la propiedad calculada solo se llama una vez y los métodos aún deben llamarse 4 veces.

Dos, el oyente

1. Uso del reloj

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue计算属性/侦听器/方法比较</title>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <h1>计算属性:computed</h1>
            {
   
   {fullName}}
            <h1>方法:methods</h1>
            {
   
   {fullName2()}}
            <h1>侦听器:watch</h1>
            {
   
   {watchFullName}}
            <h1>年龄</h1>
            {
   
   {age}}
        </div>
        <script>
            var other = 'This is other';
            var app = new Vue({
                el:"#app",
                data:{
                firstName:"zhang",
                lastName:"san",
                watchFullName:"zhangsan",
                age:18,
                },
                watch: {
                    firstName:function(newFirstName, oldFirstName){
                        console.log("firstName触发了watch,newFirstName="+newFirstName+",oldFirstName="+oldFirstName)
                        this.watchFullName = this.firstName+this.lastName+","+other
                    },
                    lastName:function(newLastName, oldLastName){
                        console.log("lastName触发了watch,newLastName="+newLastName+",oldLastName="+oldLastName)
                        this.watchFullName = this.firstName+this.lastName+","+other
                    }  
                },
                computed: {
                    fullName:function(){
                    console.log("调用了fullName,计算了一次属性")
                    return this.firstName+this.lastName+","+other;
                    }
                },
                methods: {
                    fullName2:function(){
                        console.log("调用了fullName,执行了一次方法")
                        fullName2 = this.firstName+this.lastName+","+other;
                        return fullName2;
                    }
                }
            });
        </script>
    </body>
    </html>

inicialización:

 Modificar nombre/apellido/ambos

 Modificar la edad que no se calcula en computado

 Modificar objetos fuera de la instancia de Vue

 Después de modificar el objeto fuera de la instancia de Vue, modifique el objeto dentro de la instancia de Vue

Conclusión de la prueba:

  1. El atributo nombre completo se calcula mediante calculado y el valor es nombre+apellido. Las propiedades computacionales tienen 缓存功能, cuando nombre y apellido no cambian, nombre completo no se volverá a calcular; por ejemplo, si cambiamos el valor de edad, no es necesario volver a calcular el valor de nombre completo.
  2. Los métodos no tienen funciones de almacenamiento en caché. Por ejemplo, si cambiamos el valor de edad, el método fullName2() se ejecutará nuevamente.
  3. Cuando una función se puede realizar mediante los tres métodos anteriores, obviamente es más apropiado usarla calculada, el código es simple y tiene funciones de almacenamiento en caché.
  4. El alcance del atributo calculado está dentro de la instancia de Vue, modificar el objeto externo de la instancia de Vue no recalculará la representación, pero si el objeto fuera de la instancia de Vue se modifica primero y luego se modifica el objeto del atributo calculado de Vue, el valor del objeto externo también se volverá a representar.

Propiedad calculada: calculada

     El nombre y el apellido administrados por el rango de atributos de cálculo en el nombre completo de la instancia de Vue generalmente escuchan múltiples variables 1111

Oyente: mirar

     Monitorear los cambios de datos, generalmente solo monitorear una variable o matriz

escenas a utilizar

      watch ( 异步场景), computed ( 数据联动) watch puede agregar directamente el nombre del método en forma de cadena después de los datos monitoreados

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue计算属性/侦听器/方法比较</title>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <h1>计算属性:computed</h1>
            {
   
   {fullName}}
            <h1>方法:methods</h1>
            {
   
   {fullName2()}}
            <h1>侦听器:watch</h1>
            {
   
   {watchFullName}}
            <h1>年龄</h1>
            {
   
   {age}}
        </div>
        <script>
            var other = 'This is other';
            var app = new Vue({
                el:"#app",
                data:{
                firstName:"zhang",
                lastName:"san",
                watchFullName:"zhangsan",
                age:18,
                },
                watch: {
                    firstName:function(newFirstName, oldFirstName){
                        console.log("firstName触发了watch,newFirstName="+newFirstName+",oldFirstName="+oldFirstName)
                        this.watchFullName = this.firstName+this.lastName+","+other
                    },
                    lastName:function(newLastName, oldLastName){
                        console.log("lastName触发了watch,newLastName="+newLastName+",oldLastName="+oldLastName)
                        this.watchFullName = this.firstName+this.lastName+","+other
                    },
                    watchFullName:"change"

                },
                computed: {
                    fullName:function(){
                    console.log("调用了fullName,计算了一次属性")
                    return this.firstName+this.lastName+","+other;
                    }
                },
                methods: {
                    fullName2:function(){
                        console.log("调用了fullName,执行了一次方法")
                        fullName2 = this.firstName+this.lastName+","+other;
                        return fullName2;
                    },
                    change(){
                        console.log("调用了change,触发了watch")
                        return this.watchFullName='111'
                    }
                }
            });
        </script>
    </body>
    </html>

 El método del controlador es equivalente a un evento desencadenado por un oyente normal. De los resultados, podemos ver que cuando se inicializa el componente, el oyente no tiene un método de controlador, por lo que nombre completo no tiene valor.

Al modificar el código anterior, agregue inmediato: verdadero, inmediato: verdadero significa que después de declarar el reloj, la función en el controlador se ejecutará inmediatamente. Ejecute la lógica correspondiente. Cuando se inicializa el componente, el oyente activará inmediatamente el método del controlador

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue计算属性/侦听器/方法比较</title>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
          <div>
            <p>FullName: {
   
   {person.fullname}}</p>
            <p>FirstName: <input type="text" v-model="person.firstname"></p>
          </div>
        </div>
        <script>
            var other = 'This is other';
            var app = new Vue({
              el: '#app',
               data(){
                return {
                    person: {
                        firstname: 'Menghui',
                        lastname: 'Jin',
                        fullname: ''
                    }
                }
              },
             watch: {
              person: {
                  handler(n,o){
                      this.person.fullname = n.firstname + '' + this.person.lastname;
                  },
                   immediate: true,  //刷新加载 立马触发一次handler
                  deep: true  // 可以深度检测到 person 对象的属性值的变化
              }
              }
            })
        </script>
    </body>
    </html>

Al ingresar datos en el cuadro de entrada, se puede encontrar que el valor de fullName no ha cambiado, esto se debe a que Vue no puede detectar el cambio en el valor de la propiedad interna del objeto, como el cambio de person.firstname.

Entonces, en este momento, es necesario utilizar el monitoreo profundo de Vue (profundo)

En este momento, agregue el código profundo: verdadero

Se puede encontrar que el nombre completo cambia cada vez que cambian los datos del cuadro de entrada.

De lo anterior se puede encontrar que el nuevo valor monitoreado por el controlador es el mismo que el valor anterior, esto se debe a la vacilación y homología del pozo de vue2.0, que se puede reparar con cálculos.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>

	</head>
	<body>
		<div id="app">
             <p>FullName: {
   
   {person.fullname}}</p>
             <p>FirstName: <input type="text" v-model="person.firstname"></p>
		</div>
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
		<script>
			const app = new Vue({
				el: "#app",
				data() {
					return {
						person: {
							firstname: 'Menghui',
							lastname: 'Jin',
							fullname: ''
						}
					}
				},
				methods: {

				},
				computed: {
                   person2(){
					    return JSON.parse(JSON.stringify(this.person));
				   }//解决深度监听新老值同源问题
				},
				watch:{
				   person2:{
					     handler(n,o){
							 console.log(this.person);
							 console.log(n.firstname);
					                 console.log(o.firstname);
							
							 /* this.person.fullname = this.person.firstname + this.person.lastname */
						 },
						/* immediate: true, */
						 deep: true  // 可以深度检测到 person 对象的属性值的变化
				   }
				}
			})
		</script>
	</body>
</html>

Supongo que te gusta

Origin blog.csdn.net/m0_46461853/article/details/126019079
Recomendado
Clasificación