Summary of vue data operation

  • 2021-10-13 06:31:16
  • OfStack

There are many data operation methods in vue, such as data transfer of parent-child component, data modification of parent component by child component, props, computed, watch, sync, etc. Today, we will summarize the use of these operation methods

computed is a computed attribute

computed is a computational attribute: Reduces the complexity of the template {{}}. Putting too much logic into a template makes it overweight and difficult to maintain. For any complex logic, you should use the calculation attribute to write the complex operation logic into the function of computed, and then refer to it in the template to make the logic simple and clear. How to use it: computed and data are juxtaposed, encapsulate a series of operations into a method, put it in computed, and write the method name directly when calling, without adding ()


new Vue({
 el:"#app",
 data:{
  user:{
   email:"dong@qq.com",
   nickname:"oldUath",
   phone:"12812345678"
  }
 },
 // Calculate attributes 
 computed:{
  displayName(){
    // Return 1 Results 
   const user=this.user
   return user.nickname ||user.phone||user.email
  }
 },
 template:`
   <div>
   {{displayName}}
   </div>
 `
})

watch listener

watch: Listener: Observe data changes on the Vue instance, as long as the specified data changes will execute a predetermined function when it is necessary to perform asynchronous or expensive operations when the data changes;

watch Usage 1:


<div id="app">
    {{msg}} 
    <br> 
     Has it changed ? {{isChange}}
    <button @click="change"> Change </button>
  </div>
  new Vue({
   el: "#app",
   data: {
   		// This is the first 1 Layer data 
      msg:' But you widen your view three hundred miles ',
     	isChange:'No',
      user:{
      	// This is the first 2 Layer data 
        name:"oldUath",
        phone:'18312345678'
      }
   },
   watch:{
    // As long as msg Change , This method executes , No. 1 1 Layer data only needs to be written   Data name (){} You can 
    msg(val,oldVal){
      this.isChange = 'Yes'
    },
    // No. 1 2 Layer data requirements '','user.name'(){}
    'user.name'(){
    	console.log('user.name Changed ')
    }
   },
   methods:{
    change(){
      this.msg = ' Go up 1 Floor '
    }
   }
  })

Note: In vue, if an object is assigned to him intact, then his address will change


//obj:{a:'a'}
obj.a+='hi'// Is the monitoring obj When, because obj The address has not changed, so no listening will be performed obj Events of 

You can use deep: true. This means letting watch listen deep. If the value changes, it will change


watch:{
	obj(){
  		handle(){console.log('obj Changed ')
  	},
  	 deep:true
}

Usage 2: vm. $watch ('Listening variable', called function, {immediate: true})

Same effect as Method 1


const vm = new Vue({
   el: "#app",
   data: {
      msg:' But you widen your view three hundred miles ',
     	isChange:'No',
      user:{
        name:"oldUath",
        phone:'18312345678'
      }
   },
   methods:{
    change(){
      this.msg = ' Go up 1 Floor '
    }
   }
  })
  vm.$watch('msg',function(){
  		console.log('n Changed ')
  },{immediate:true})

Parent component passes data to child component: Props

If the parent component wants to pass in data to the child component, it needs to use Props to introduce variables in the child component type

The parent component should enter and exit the child component money= "100"
First, pass in the parent component species


// Calling a child component on a parent component 
<Child :money="100"><Child>

Then introduce data in the sub-component species and introduce the variable money


<template>
<div class="red">
+  {{money}} Yuan 
 <button> Spend money </button>
</div>
</template>
<script>
export default {
+ props:['money']
}
</script>

At this time, the child component can only use the data of the parent component, but cannot modify it

The child component modifies the data of the parent component (. sync principle)

Component cannot directly modify data outside props

Modify with $emit

Use $emit in subcomponents ('Parameter 1', Parameter 2)

The current instance inherits eventBus and can trigger 1 event

Write $emit in the subcomponent, the first parameter is the event name, and the second parameter is the modified value


<!-- $emit() Trigger 1 Events, update:money Is the event name   -->
<button @click="$emit('update:money',money-10)"> Spend money </button>

Accept parameter 2 with $event in the parent component;

$event is the one that receives the result returned by subcomponent parameter 2


<!--   Pass to subcomponents 1 A money Value ,v-on Is the listening subcomponent's update:money Events, 
      $event Get the result of a child component event -->
  <Child :money="total" v-on:update:money="total = $event" />

Simplified result: sync

This 1 piece of code of parent component is too troublesome, and vue encapsulates it as a modifier


  <Child :money.sync="total" />

Subcomponents are still written like that

This only solves the communication problem of parent-child components. What about the communication problem of brother components?

Sister Component Communication: emit/emit/on

In this method, an empty Vue instance is used as the central event bus (event center), which is used to trigger events and listen to events, and the communication between any components is skillfully and lightweight, including parent-child, brother and cross-level. When our project is large, we can choose the better state management solution vuex. Specific implementation mode


<div id="app">
    {{msg}} 
    <br> 
     Has it changed ? {{isChange}}
    <button @click="change"> Change </button>
  </div>
  new Vue({
   el: "#app",
   data: {
   		// This is the first 1 Layer data 
      msg:' But you widen your view three hundred miles ',
     	isChange:'No',
      user:{
      	// This is the first 2 Layer data 
        name:"oldUath",
        phone:'18312345678'
      }
   },
   watch:{
    // As long as msg Change , This method executes , No. 1 1 Layer data only needs to be written   Data name (){} You can 
    msg(val,oldVal){
      this.isChange = 'Yes'
    },
    // No. 1 2 Layer data requirements '','user.name'(){}
    'user.name'(){
    	console.log('user.name Changed ')
    }
   },
   methods:{
    change(){
      this.msg = ' Go up 1 Floor '
    }
   }
  })
0

For example, an A component passes information to an C component, and ABC is an adjacent component

First, use $emit to provide event data in A component, and the first parameter is the data name, which is the same as the first parameter of on receiving data; The second parameter is the data


<div id="app">
    {{msg}} 
    <br> 
     Has it changed ? {{isChange}}
    <button @click="change"> Change </button>
  </div>
  new Vue({
   el: "#app",
   data: {
   		// This is the first 1 Layer data 
      msg:' But you widen your view three hundred miles ',
     	isChange:'No',
      user:{
      	// This is the first 2 Layer data 
        name:"oldUath",
        phone:'18312345678'
      }
   },
   watch:{
    // As long as msg Change , This method executes , No. 1 1 Layer data only needs to be written   Data name (){} You can 
    msg(val,oldVal){
      this.isChange = 'Yes'
    },
    // No. 1 2 Layer data requirements '','user.name'(){}
    'user.name'(){
    	console.log('user.name Changed ')
    }
   },
   methods:{
    change(){
      this.msg = ' Go up 1 Floor '
    }
   }
  })
1

The C component accepts data $on, the first parameter is the data name, and the second parameter is used to receive the data


<div id="app">
    {{msg}} 
    <br> 
     Has it changed ? {{isChange}}
    <button @click="change"> Change </button>
  </div>
  new Vue({
   el: "#app",
   data: {
   		// This is the first 1 Layer data 
      msg:' But you widen your view three hundred miles ',
     	isChange:'No',
      user:{
      	// This is the first 2 Layer data 
        name:"oldUath",
        phone:'18312345678'
      }
   },
   watch:{
    // As long as msg Change , This method executes , No. 1 1 Layer data only needs to be written   Data name (){} You can 
    msg(val,oldVal){
      this.isChange = 'Yes'
    },
    // No. 1 2 Layer data requirements '','user.name'(){}
    'user.name'(){
    	console.log('user.name Changed ')
    }
   },
   methods:{
    change(){
      this.msg = ' Go up 1 Floor '
    }
   }
  })
2

Summarize

Use for transferring data between father and son props And $emit Use for transmitting data between brothers $emit And $on Parent component passes data to grandchild component using provide And inject

The above is the vue data manipulation related summary details, more information about vue data manipulation please pay attention to other related articles on this site!


Related articles: