search
HomeWeb Front-endVue.jsLet's talk about how to implement two-way binding in Vue without using v-model?

What if two-way binding is not implemented through v-model in Vue? The following article will introduce to you how to achieve two-way binding without using v-model. I hope it will be helpful to you!

Let's talk about how to implement two-way binding in Vue without using v-model?

#How to achieve two-way binding without using v-model?

Some people say that you have the nerve to ask such a novice question?

Don’t tell me, when I first learned vue, I was tortured to death by these problems. I bit the bullet and wrote according to the official website document demo. After I became able to use it, I also wrote a lot of v-model in daily development. After I made up my mind to study the related bugs carefully, I found that there are still many ways to do it. Let me explain in detail. [Related recommendations: vue.js video tutorial]

Let’s look at the answer first:

<template>
  <div class="test-v-model">
    <p>使用v-model</p>
    <input v-model="msg" placeholder="edit me" />
    <p>{{ msg }}</p>

    <p>不使用v-model</p>
    <input :value="msg1" @input="handleInput" placeholder="edit me" />
    <p>{{ msg1 }}</p>
  </div>
</template>

<script>
export default {
  name: &#39;test-v-model&#39;,
  data() {
    return {
      msg: &#39;&#39;,
      msg1: &#39;&#39;
    }
  },
  methods: {
    handleInput(e) {
      this.msg1 = e.target.value
    }
  }
}
</script>

Do not use v- model, you need to bind the value through the value attribute and change the binding value through the input event to achieve two-way binding.

In other words, v-model is just a shorthand form

In fact, the essence of v-model is syntactic sugar. It is responsible for monitoring user input events to update data. , and perform some special processing on some extreme scenes. -- Official documentation

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 will have value as prop and change as event.
  • Two-way binding
  • One-way data binding
  • vue component One-way data flow for interaction between

#Q: What is two-way binding?

#Two-way binding means that when the data changes, the view is updated synchronously. When the view changes, the data will also be updated.

Q: What is one-way data binding?

One-way data binding means when the data changes , the view is updated synchronously, and when the view changes, the data will not be updated.

In vue, two-way binding is achieved through the instruction v-model, and one-way data binding is achieved through v-bind

After reading the following code and the gif demonstration of this code running, you will be able to understand their differences.

<template>
  <div>
    <p>双向绑定</p>
    <input v-model="msg" placeholder="edit me" />
    <p>{{ msg }}</p>

    <p>单向数据绑定</p>
    <input v-bind:value="msg1" placeholder="edit me" />
    <p>{{ msg1 }}</p>
  </div>
</template>

<script>
export default {
  name: &#39;test-v-model&#39;,
  data() {
    return {
      msg: &#39;&#39;,
      msg1: &#39;&#39;
    }
  }
}
</script>

Lets talk about how to implement two-way binding in Vue without using v-model?

As can be seen from the gif diagram, using v-model, when the data changes, the view is updated synchronously. When the view changes, the data will also be updated. This is Two-way binding.

Using v-bind, when the data changes, the view is updated synchronously. When the view changes, the data will not be updated. This is one-way data binding.

Q: What is vue one-way data flow?

A child component cannot change the prop attribute passed to it by the parent component. The recommended approach is for it to throw an event and notify the parent component to change the bound value on its own.
To sum up, data goes down and events go up.

The vue document puts forward the concept of one-way data flow when introducing Prop. Click here to view the vue document's description of one-way data flow.

All props form a One-way downward binding between their parent and child props: The update of the parent prop will flow downward to the child component, but in reverse Coming here is not possible. This will prevent the child component from accidentally changing the state of the parent component, making the data flow of your application difficult to understand.

In addition, every time the parent component changes, all props in the child component will be refreshed to the latest values. This means that you should not change props inside a child component. If you do this, Vue will issue a warning in the browser's console.

Let’s look at the following example:

The subcomponent directly performs two-way binding on the prop value. What will happen?

Parent component code:

<template>
  <child-component :value="fatherValue" />
</template>

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

export default {
  name: &#39;father-component&#39;,
  components: {
    ChildComponent
  },
  data() {
    return {
      fatherValue: &#39;&#39;
    }
  }
}
</script>

Child component code:

<template>
  <div class="child-component">
    <input v-model="value" placeholder="edit me" />
    <p>{{ value }}</p>
  </div>
</template>

<script>
export default {
  name: &#39;child-component&#39;,
  props: {
    value: {
      type: String,
      default: &#39;&#39;
    }
  }
}
</script>

Lets talk about how to implement two-way binding in Vue without using v-model?

Lets talk about how to implement two-way binding in Vue without using v-model?

Lets talk about how to implement two-way binding in Vue without using v-model?

可以看到,childComponent中的 prop 值可以实现双向绑定,但是 FatherComponent 中的 data 值并未发生改变,而且控制台抛出了警告:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"

翻译一下:避免直接改变 prop 值,因为每当父组件重新渲染时,该值将被覆盖。相反,使用基于 prop 值的 data 或 computed。

很显然,直接改变子组件的 prop 值的这种行为被 vue 禁止了。

如何操作传入子组件的 prop 值

但是很多时候,我们确实要操作传入子组件的 prop 值,该怎么办呢?

正如上面的警告所说,有两种办法:

  • 这个 prop 用来传递一个初始值,定义一个本地的 data property 并将这个 prop 用作其初始值
props: {
  initialCounter: {
    type: Number,
    default: 0
  },
},
data() {
  return {
    counter: this.initialCounter
  }
}
  • 这个 prop 以一种原始的值传入且需要进行转换,用这个 prop 的值来定义一个计算属性
props: {
  size: {
    type: String,
    default: &#39;&#39;
  }
},
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

这样不管怎么操作数据都是操作的子组件数据了,不会影响到父组件数据。

所以,我们想用 prop 传入的数据实现双向绑定,可以这么写:

父组件代码不变

子组件里用 innerValue 来接收传入的 value :

<template>
  <div class="child-component">
    <input v-model="innerValue" placeholder="edit me" />
    <p>{{ innerValue }}</p>
  </div>
</template>

<script>
export default {
  name: &#39;child-component&#39;,
  props: {
    value: {
      type: String,
      default: &#39;&#39;
    }
  },
  data() {
    return {
      innerValue: this.value
    }
  }
}
</script>

这里要注意一个问题

在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变变更这个对象或数组本身将会影响到父组件的状态。

还是上面的例子,我们将传入的值改为对象:

父组件代码:

<template>
  <child-component :obj="fatherObj" />
</template>

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

export default {
  name: &#39;father-component&#39;,
  components: {
    ChildComponent
  },
  data() {
    return {
      fatherObj: {
        name: &#39;lin&#39;
      }
    }
  }
}
</script>

子组件代码:

<template>
  <div class="child-component">
    <input v-model="innerObj.name" placeholder="edit me" />
    <p>{{ innerObj.name }}</p>
  </div>
</template>

<script>
export default {
  name: &#39;child-component&#39;,
  props: {
    obj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      innerObj: this.obj
    }
  }
}
</script>

Lets talk about how to implement two-way binding in Vue without using v-model?

Lets talk about how to implement two-way binding in Vue without using v-model?

这里的 this.obj 是引用类型,赋值给了 innerObj,所以 innerObj 实际上还是指向了父组件的数据,对 innerObj.name 的修改依然会影响到父组件

所以,处理这种引用类型数据的时候,需要深拷贝一下

import { clone } from &#39;xe-utils&#39;
export default {
  name: &#39;child-component&#39;,
  props: {
    obj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      innerObj: clone(this.obj, true)
    }
  }
}

Lets talk about how to implement two-way binding in Vue without using v-model?

如上图所示,这样子组件和父组件之间的数据就不会互相影响了。

总结

至此,终于把双向绑定和单向数据流讲清楚了,真的没想到,平时开发时都懂的概念,想讲清楚居然花了这么多篇幅,确实不容易,不过,这也是对自己的一种锻炼吧。

问:v-model是双向绑定吗?

是,但只是语法糖

问:v-model是单向数据流吗?

是,数据向下,事件向上

本题还有一些其他问法,比如:

  • vue 的双向绑定和单向数据流有什么区别?
  • 为什么说 vue 的双向绑定和单向数据流不冲突?

看完本篇文章,相信不管怎么问,你都能对这两个概念理解透彻了。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about how to implement two-way binding in Vue without using v-model?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools