Vue parent component and sub-assembly share the same value, change parent component may change over time in the subassembly, the subassembly changes will change at any time within parent components

Component code // Parent 
<
Template > < div > < input V-Model = "Place" /> < Button @click = "updatePlace" > modified input content </ Button > < Home ChIL- : Place = 'Place' @onChange = "onChange" : width = 'inputWidth' @ click.native = "changeNative" /> // @ click.native component is bound to the native event </ div > </ Template > <script> import HomeChil from './HomeChil' export default { name: "Home", data(){ return{ inputWidth:100, Place: ' value input box of " } }, components:{ HomeChil }, methods:{ updatePlace(val){ the this .place = ' parent element content changes in input ' ; the this .inputWidth = the this .inputWidth + 100 ; }

// get passed to the method of the subassembly, the subassembly can call this method to give the parent component onChange(val){
this.place=val }, changeNative(){ console.log('dd'); } } }; </script> <style> </style>

// get the code subassembly
<
Template > < div style = "border: 1px Solid Red" >
      <Span> When the value in the parent component member changes I will become: {{inputName}} </ span> 
    <input v-model="inputName" @change="onChangeInput" :style="style"/>
    <button @click="changeInput">改变input中的内容</button>
  </div>
</template>

<script>
export default {
  name: "HomeChil",
  props:{
      width:Number,
      place:String,
  },
  data() {
    return {
      inputName: this.place
    };
  },
  computed: { 
// dynamically add style style(){
return{ width:this.width+'px' } } }, created() { }, watch: { site (val) { this.inputName = val; }, inputName(val) { this.$emit("onChange", val); } }, methods: { changeInput() { the this .inputName = " subassembly Found changed " ; } } }; </script> <style> </style>

note:

       1. assigned to a new variable in the variable component provided a new, pass over the parent component values ​​inputName: this.place;

       2. Sometimes the data, transmitted not directly write dead, but dynamic data from the parent element, then the instruction may be used to dynamically bind the V-bind value of props, watch and listen with the parent component subassembly pass over the value, the value is assigned to a new variable, time data changes when the parent element, is also transmitted to the subassembly. In the sub-assembly with the inputName listening watch, when it changes the onChange method call parent element, the changed values ​​to the parent element, the value will be assigned to the parent component in place

 

     

Guess you like

Origin www.cnblogs.com/lvlvlv/p/11642115.html