Getting to know Vue2: form input binding (with Demo)

Online demonstration

http://demo.xiongze.net/

Download address

https://gitee.com/xiongze/Vue2.git

js reference

<!--Here you can download the reference by yourself or use external dynamic link reference-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

Basic usage

You can use the v-model command to create two-way data binding on forms, and elements. It will automatically select the correct method to update the element according to the control type.

Despite some magic, v-model is essentially just a grammar sugar. It is responsible for monitoring user input events to update data, and some special processing for some extreme scenarios.

v-model will ignore the initial values of value, checked and selected attribute s of all form elements, and always take the data of Vue instances as the data source.

You should declare the initial value in the data option of the component through JavaScript.

v-model internally uses different properties for different input elements and throws different events:

text and textarea elements use value property and input events;
checkbox and radio use checked property and change events;
The select field takes value as a prop and change as an event.
For languages that need to use input methods (such as Chinese, Japanese, Korean, etc.), you will find that v-model will not be updated during the text combination of input methods.

If you also want to handle this process, use the input event.

Click the event and prompt box

HTML

<div id="example">
  <button v-on:click="say('I'm the button. You clicked me')">Button click</button>
</div>

JS

Copy code
//An instance of vue
new Vue({
    el: '#example',
    data: {
        msg: 'Hello!'
    },
   //Functions (for pop ups)
     methods: {
        say: function (i) {
            alert(i)
        }
      },
});

Computer properties and listeners

1. Computer properties

HTML

<div id="example">
  <div>Calculation properties:{{toUp}}</div>
  <inputtype="text" v-model="ipt2">
</div>

JS

//An instance of vue
        new Vue({
            el: '#example',
            data: {
                msg: 'Hello!',
                ipt: 'I am a computer attribute'
            },

            //Calculation properties
            computed: {
                toUp: function () {
                    var that = this;
                    var temp = that.ipt;
                    return temp;
                }
            },
        });

Here we declare a calculation attribute toUp

You can bind the calculation property in the template as you bind the ordinary property.

2. Listener

Although computed properties are more appropriate in most cases, sometimes a custom listener is required.

This is why Vue provides a more general way to respond to changes in data through the watch option.

This approach is most useful when asynchronous or expensive operations need to be performed when data changes.

HTML

<div id="example">
  <input type="text" v-model="ipt2">
</div>

JS

//An instance of vue
        new Vue({
            el: '#example',
            data: {
                msg: 'Hello!',
                ipt2: 'I'm an observer(Listener)'
            },
          //Functions (for pop ups)
            methods: {
                say: function (i) {
                    alert(i)
                }
            },

            //Observer
            watch: {
                // If 'ipt2' changes, this function will run
                ipt2: function (newVal) {
                    this.say(newVal)
                    //console.log(this.ipt2);
                }
            }
        });

Using the watch option allows us to perform an asynchronous operation (access an API), limits how often we perform the operation, and sets the intermediate state before we get the final result. These are things that computational properties cannot do.

In addition to the watch option, you can also use the imperative VM$ watch API.

text

HTML

<div id="example">
   <input v-model="message" placeholder="Single line text">Value entered: {{ message }}
</div>

JS

//An instance of vue
new Vue({
    el: '#example',
    message :"",
});

Multiline text

HTML

<div id="example">
   <textarea v-model="message" placeholder="Multiline text"></textarea><br />
    <span>Value entered:</span>
    <p style="white-space: pre-line;">{{ message }}</p>
</div>

JS

//An instance of vue
new Vue({
    el: '#example',
    message :"",
});

Custom component (simple): output the specified content

When registering a component, we always need to give it a name. For example, when registering globally, we have seen:

Vue.component('my-component-name', { /* ... */ })
The component name is Vue The first parameter of the component.

The name you give a component may depend on what you intend to do with it.

When using a component directly in the DOM (instead of a string template or a single file component),

We strongly recommend following the custom component name in the W3C specification (all lowercase letters and must contain a hyphen).

This will help you avoid conflicts with current and future HTML elements.

You can find other suggestions on component names in the style guide.

HTML

<div id="example">
  <simple></simple>
</div>

JS

// Register a global custom component simple
Vue.component("simple", Vue.extend({
    template: '<div>I am a div Block Oh</div>'
}));

//An instance of vue
new Vue({
    el: '#example'
});

Custom component (complex): output an ul unordered list

HTML

<div id="example">
  <do-list v-bind:data="list">

   </do-list>
</div>

JS

// Register a complex global custom [component] do list
Vue.component("do-list", Vue.extend({
    //(parent-child parameter passing) the subcomponent should explicitly declare its expected data with props option:
    props: ['data'],
    template: `
    <ul>
        <li v-for="item in data">{{item.name}}</li>
    </ul>
`
}));

//An instance of vue
new Vue({
    el: '#example',
    list: [
        { name: 'Journey to the West', author: 'Wu Chengen' },
        { name: 'The Dream of Red Mansion', author: 'Cao Xueqin' },
        { name: 'Water Margin', author: 'Shi Naian' },
        { name: 'Romance of the Three Kingdoms', author: 'Luo Guanzhong' }
     ],
});

check box

HTML

<div id="example">
    <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
    <label for="jack">Jack</label>
    <input type="checkbox" id="john" value="John" v-model="checkedNames">
    <label for="john">John</label>
    <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
    <label for="mike">Mike</label>
    <span>Selected value: {{ checkedNames }}</span>
</div>

JS

//An instance of vue
new Vue({
    el: '#example',
    checkedNames: [],   //Multiple choice
});

radio button

HTML

<div id="example">
    <input type="radio" id="one" value="One" v-model="picked">
    <label for="one">One</label>
    <input type="radio" id="two" value="Two" v-model="picked">
    <label for="two">Two</label>
    <span>Selected value: {{ picked }}</span>
</div>

JS

//An instance of vue
new Vue({
    el: '#example',
    picked: '',    //Single choice
});

Drop down selection box

HTML

<div id="example">
    <select v-model="selected">
        <option disabled value="">Please select</option>
        <option>Vue 1.x</option>
        <option>Vue 2.x</option>
        <option>Vue 3.x</option>
    </select>
    <span>Selected value: {{ selected }}</span>
</div>

JS

//An instance of vue
new Vue({
    el: '#example',
    selected: ''  //Radio 
});

If the initial value of the v-model expression does not match any options, the element is rendered as "unchecked".

In iOS, this prevents the user from selecting the first option. Because in this case, iOS will not trigger the change event.

Therefore, it is more recommended to provide a disabled option with a blank value as above.

Welcome to subscribe to WeChat public official account.
Author: Kumasawa, official account of pain and happiness in learning: Xiong Zi has something to say.
source: https://www.cnblogs.com/xiongze520/p/14764147.html
It is not easy to create. If anyone, group or organization reprints or excerpts all or part of it, please indicate the author and the link to the original text in the obvious position of the article.

Keywords: Vue Vue.js

Added by iamcaper on Thu, 10 Feb 2022 10:25:48 +0200