Home >Web Front-end >Vue.js >Detailed explanation of how to implement two-way binding of data using Vue

Detailed explanation of how to implement two-way binding of data using Vue

青灯夜游
青灯夜游forward
2023-04-19 18:49:3710766browse

In Vue.js, two-way data binding is a very powerful feature. It can keep data and views synchronized, allowing developers to operate data more conveniently. In this article, we will introduce how to implement two-way binding of data with Vue.js.

Detailed explanation of how to implement two-way binding of data using Vue

1. Understanding two-way binding

First, we need to understand the principle of two-way binding. In Vue.js, data and views are connected through ViewModel (view model). When the data changes, the ViewModel automatically updates the view. When the view changes, the ViewModel will automatically update the data. [Related recommendations: vuejs video tutorial, web front-end development]

2. Use the v-model command

Vue .js provides the v-model directive to implement two-way binding of data. The v-model directive can be used to bind values ​​to form elements and components.

For example, using the v-model directive on an input element can achieve two-way binding of data:

<template>
  <div>
    <input type="text" v-model="message">
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: &#39;Hello, Vue.js!&#39;
    }
  }
}
</script>

In the above example, we use an input element to bind the message attribute , use {{ message }} to display bound data.

When we enter text, the data and view will automatically update synchronously. This is how the v-model directive implements two-way data binding.

3. Use custom components to achieve two-way binding

In addition to form elements, we can also use custom components to achieve two-way binding of data.

First, we need to define a custom component and bind data using the v-model directive. Then, we need to define a prop named value in the component and use the $emit() method in the component to trigger an event named input. In this way, you can use the v-model directive in the parent component to bind the value of the custom component.

For example, the following is a custom number input box component:

<template>
  <div>
    <input type="number" :value="value" @input="$emit(&#39;input&#39;, $event.target.value)">
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 0
    }
  }
}
</script>

In the above example, we use an input element to bind the value attribute, and use $ when inputting The emit() method triggers an event named input.

Now, we can use the v-model directive in the parent component to bind the value of the custom component:

<template>
  <div>
    <custom-input v-model="count"></custom-input>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script>
import CustomInput from &#39;./CustomInput.vue&#39;

export default {
  components: {
    CustomInput
  },
  data() {
    return {
      count: 0
    }
  }
}
</script>

In front-end development, two-way binding of data is a very common needs. As a popular JavaScript framework, Vue.js provides a very convenient way to achieve two-way binding of data. This article will introduce how Vue.js implements two-way binding of data.

4. Data hijacking

Vue.js uses data hijacking to achieve two-way binding of data. It hijacks the setter and getter methods of object properties by using the Object.defineProperty() method in ES5. In this way, when the properties of the object change, Vue.js can listen to the change and synchronize the change to the view.

For example, we can define a class named Person and then hijack its properties through the Object.defineProperty() method:

class Person {
  constructor(name, age) {
    this._name = name
    this._age = age
  }

  get name() {
    return this._name
  }

  set name(name) {
    this._name = name
  }

  get age() {
    return this._age
  }

  set age(age) {
    this._age = age
  }
}

let person = new Person(&#39;Tom&#39;, 18)

Object.defineProperty(person, &#39;name&#39;, {
  get() {
    console.log(&#39;getting name&#39;)
    return this._name
  },
  set(name) {
    console.log(&#39;setting name&#39;)
    this._name = name
  }
})

Object.defineProperty(person, &#39;age&#39;, {
  get() {
    console.log(&#39;getting age&#39;)
    return this._age
  },
  set(age) {
    console.log(&#39;setting age&#39;)
    this._age = age
  }
})

person.name = &#39;Jerry&#39;
console.log(person.name)

In the above code, we pass the Object.defineProperty() method To hijack the name and age attributes of the Person class. When we assign a value to the name attribute of the person object, the setter method is triggered and 'setting name' is output. When we read the name attribute of the person object, the getter method is triggered, and 'getting name' is output and _name is returned. The value of the attribute.

5. Template engine

Vue.js uses a template engine to parse DOM templates and generate virtual DOM. Virtual DOM is a lightweight JavaScript object used to describe the real DOM tree. Vue.js implements two-way binding of data by operating on the virtual DOM.

For example, we can define an object containing name and age properties and use the Vue.js template engine to render it on the page:

<div id="app">
  <p>姓名:<input v-model="person.name"></p>
  <p>年龄:<input v-model="person.age"></p>
  <p>您的姓名是:{{ person.name }}</p>
  <p>您的年龄是:{{ person.age }}</p>
</div>
const app = new Vue({
  el: &#39;#app&#39;,
  data: {
    person: {
      name: &#39;Tom&#39;,
      age: 18
    }
  }
})

6.Object. defineProperty() detailed explanation

The core principle of Vue.js to implement two-way binding is to use the Object.defineProperty() method to monitor data changes. This method receives three parameters, namely object, attribute name and attribute descriptor. We can use this method to define a property and do some operations in the property's getter and setter.

The steps to implement two-way binding in Vue.js are as follows:

  1. Create a Vue instance and define a data object that contains the data that requires two-way binding. For example:
javascriptCopy code
var vm = new Vue({
  data: {
    message: &#39;&#39;
  }
})
  1. In HTML, two-way binding of data is achieved by using the v-model directive. For example:
htmlCopy code
<input type="text" v-model="message">
  1. In the Vue instance, use the Object.defineProperty() method to monitor changes in the message property in the data object, as shown below:
javascriptCopy code
Object.defineProperty(vm, &#39;message&#39;, {
  get: function () {
    return this._message
  },
  set: function (newValue) {
    this._message = newValue
    // ...执行一些操作
  }
})

In the above code, we use a variable _message starting with an underscore to store the actual data. In getters and setters, we get and set data by accessing _message, and we can perform some operations in setters.

另外,在 Vue.js 中,我们还可以使用 watch方法来监听数据的变化。watch 方法来监听数据的变化。watch 方法接收两个参数,第一个参数是需要监听的属性,第二个参数是回调函数,回调函数会在数据变化时执行。

下面是一个完整的 Vue.js 双向绑定的示例代码:

<div id="app">
  <input type="text" v-model="message">
  <p>您输入的内容是:{{ message }}</p>
</div>
var vm = new Vue({
  el: &#39;#app&#39;,
  data: {
    message: &#39;&#39;
  }
})

Object.defineProperty(vm, &#39;message&#39;, {
  get: function () {
    return this._message
  },
  set: function (newValue) {
    this._message = newValue
    console.log(&#39;您输入的内容是:&#39; + this._message)
  }
})

在上面的代码中,我们创建了一个 Vue 实例,并且使用 v-model 指令来实现数据的双向绑定。然后,我们使用 Object.defineProperty() 方法来监听数据的变化,并且在 setter 中输出数据到控制台。

通过上面的代码示例,我们可以看到 Vue.js 实现数据的双向绑定非常简单,而且使用起来也非常方便。

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of Detailed explanation of how to implement two-way binding of data using Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete