This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

preface

Today we will look at data binding, Ref, when the development of data binding is called almost everywhere it figure! Ref is used to register references to elements or child components! Straight up!

Form data binding

introduce

In development we often need to create form elements whose contents are controlled by the data in the Vue instance. User input actions on the form can modify the data in the instance. The above behavior is called bidirectional binding of the form.

Example: The following code is an example of input implementing two-way binding of forms

<div id="app">
        <input v-bind:value="str" @input="inputHandel">
        {{str}}
</div>

<script>
        new Vue({
            el: "#app".data: {
                str: 'hello world'
            },
            methods: {
                inputHandel(evt) {
                    this.str = evt.target.value 
                }
            }
        })
</script>
Copy the code

To simplify data binding of form elements, Vue uses the value attribute for input select Textarea value bindings

But a single check box is still a checked property

<div id=app>    
    <input v-bind:value="str" @input="inputHandel">
    {{str}}
    <textarea :value="str"></textarea>
    <select :value="city">
        <option value="bj">Beijing</option>
        <option value="sh">Shanghai</option>
        <option value="gz">Guangzhou</option>
        <option value="sz">shenzhen</option>
    </select>
    
    <input type="checkbox" :checked="true">
</div>

<script>
        new Vue({
            el: "#app".data: {
                str: 'hello world'.city: 'sz'
            },
            methods: {
                inputHandel(evt) {
                    this.str = evt.target.value 
                }
            }
        })
</script>
Copy the code

While Vue helps make it easier for form elements to be bound, there are still some gaps between different form elements. Because of these differences, the form is bound in both directions, with different properties and methods bound for different form elements. In this case, Vue helps us with the form differences by providing a v-model directive, which is essentially just syntax sugar. It is responsible for listening for user input events to update the data, and does some special handling for extreme scenarios.

Syntax: v-model=”data attribute”

<div id="app">

    <input v-model="str">
    {{str}}
    <textarea v-model="str"></textarea>
    <p>{{city}}</p>
    <select v-model="city">
        <option value="bj">Beijing</option>
        <option value="sh">Shanghai</option>
        <option value="gz">Guangzhou</option>
        <option value="sz">shenzhen</option>
    </select>
    <p>{{agree? 'agree' : 'Disagree '}}</p>
    <input type="checkbox" v-model="agree">
</div>

<script>
    new Vue({
        el: "#app".data: {
            str: 'hello world'.city: 'sz'.agree: false}})</script>
Copy the code

Note: When v-Model binding supports check form elements, use array types for v-Model binding data

// When the checkable property is set, the selector automatically converts the data in the V-Model into an array
 <select v-model="city" multiple>
            <option value="" disabled>Please choose your city</option>
            <option value="bj">Beijing</option>
            <option value="sh">Shanghai</option>
            <option value="gz">Guangzhou</option>
            <option value="sz">shenzhen</option>
 </select>
 
 To implement checkboxes, you must set the data in the V-Model to an array
 <p>Hobby {{hobbys}}</p>[] <label> Smoking <input type="checkbox" value="Smoking" v-model="hobbys"<input type=" hobbys" value=" hobbys"> </label> <input type=" hobbys" value=" hobbys"> </label> <input type=" hobbys" value=" hobbys" value=" hobbys"> </label> <input type=" hobbys" </label> <input type="checkbox" value=" hobbys" value=" hobbys">Copy the code

The modifier

.lazy

By default, v-Model synchronizes the value of the input box with the data after each input event (except when the text is combined with the input method above). You can add the lazy modifier to convert the synchronization to _ after the change event _ :

<! -- Update when 'change' is not 'input' --><input v-model.lazy="msg">
Copy the code

.number

To automatically convert the user’s input to a numeric type, add the number modifier to the V-model:

<input v-model.number="age" type="number">
Copy the code

This is often useful because the value of the HTML input element is always returned as a string, even when type=”number”. If the value cannot be resolved by parseFloat(), the original value is returned.

.trim

To automatically filter the first and last whitespace characters entered by the user, add the trim modifier to the V-Model:

<input v-model.trim="msg">
Copy the code

Ref

introduce

Vue provides a ref attribute to a component element. A component element bound to the REF attribute can access its real DOM node (label element) or instance object (component) in the current Vue instance object via $refs.

Use refs in native HTML tags

This.$refs. The variable name accesses its real DOM node

 <div id="app">
        <audio ref="myAudio" src="./ potion song. Mp3" controls></audio>
        <button @click="showAudio">show</button>
 </div>   
 
<script>
 new Vue({
     el: '#app'.methods: {
         showAudio() {
             console.log(this.$refs.myAudio)
         }           
    }
})
</script> 
Copy the code

Use the REF in the component

Syntax:
Current component internal this.$refs. The variable name accesses the instance object of the child component to get the properties and methods of the component instance. (Avoid this pattern because it increases coupling between components.)

<Demo ref="myDemo" />
<script>
import Demo from './components/Demo'

export default {
  name: 'App'.methods: {
    show() {
      // The methods of the child Demo are called in the parent component
      this.$refs.myDemo.sayHello()
    }
  },
  components: {
    Demo
  }
}
</script>
Copy the code

Pay attention to

1. Each label or component in a vue instance can set the REF attribute, and any number of elements can be bound to the REF attribute

<div id="app">
        <audio ref="myAudio" src="./ potion song. Mp3" controls></audio>
        <button ref="myBtn" @click="showAudio">show</button>
        <p ref="textEl">text</p>
</div>  
$refs = this. Refs = this.$refs = this
Copy the code

2. When refs is used with list rendering (V-for),$refs returns an array containing all the rendered elements of the list

<div id="app">
   // The return value of the same level of v-for is a list rendering of the current array of elements
    <p v-for="num in arr" :key="num" ref="numList">// The return value of the ref inside the v-for is also a list rendering of the current array of elements<span ref="spanList">{{num}}-span</span>
        <a>It's no use a</a>
        {{num}}
    </p>
    <button @click="showRefList">click</button>
</div>

<script>
    new Vue({
        el: '#app'.data: {
            arr: [1.2.3.4.5]},methods: {
            showRefList() {
                // [p,p,p,p,p]
                console.log(this.$refs.numList,
                 this.$refs.spanList)
                 //[span,span,span,span,span]  }}})</script>
Copy the code

At the end

That’s all for today! See you next time! Code word is not easy, feel good can move little finger thumbs up what yo ~

series

Vue series

  • Starting Vue Configuration (1)
  • Vue Event Binding (2)
  • Vue Rendering instruction (3)
  • Vue Animation Transition (4)
  • Vue-todo Case (5)
  • Vue Form data binding, Ref (6)
  • Vue components
  • Vue slot & filter
  • Vue backpass value ($EMIT event)

Vue – the Router series

  • Installation and use of vue-Router
  • Vue-router Routes configuration

Vuex series

  • Vuex series (I) — the use of Vuex
  • Vuex series (ii) — The use of modularity
  • Vuex Series (III) — the difference and usage of store.com MIT and Store. dispatch
  • Vuex series (IV) — Auxiliary function mapMutations analysis