如何为自定义Vue.js组件添加`v-model`支持

news/2024/7/7 19:30:16

介绍 (Introduction)

The v-model directive is one of the few directives that comes bundled with Vue.js. This directive allows for two-way data binding between our data and views.

v-model指令是Vue.js附带的少数几个指令之一。 该指令允许在我们的数据和视图之间进行双向数据绑定。

With two-way data binding, when we update our data via input fields or other controls, we can modify the DOM without having to do DOM work.

通过双向数据绑定,当我们通过输入字段或其他控件更新数据时,我们可以修改DOM,而无需执行DOM工作。

In this article you’ll explore how this directive works and use it for your own components.

在本文中,您将探索此指令的工作方式并将其用于您自己的组件。

v模型在内部如何工作 (How v-model works internally)

From our knowledge of HTML, we know that input, select, textarea are the main ways we feed data to our application.

根据对HTML的了解,我们知道inputselecttextarea是将数据馈送到应用程序的主要方式。

For v-model to work, it expects the element or component in question to receive a prop (default is value) and also emit an event (default is input.)

为了使v-model正常工作,它希望所讨论的元素或组件能够接收prop(默认值为value)并发出事件(默认为input)。

Depending on the element, Vue decides how to listen and handle the data. For input elements, you might use v-model like this:

根据元素的不同,Vue决定如何监听和处理数据。 对于input元素,可以这样使用v-model

<input v-model="email" />

v-model translates to this:

v-model转换为:

<input :value="email" @input="e => email = e.target.value" />

Vue uses this expansion to handle textarea, select and some other input types.

Vue使用此扩展来处理textareaselect和其他一些input类型。

For radio buttons and checkboxes, Vue uses their checked prop and listens for their change event.

对于单选按钮和复选框,Vue使用其checked道具并监听其change事件。

For elements like select tags and checkboxes that can accept multiple values, Vue will automatically return an array of selected values.

对于可以接受多个值的元素(如select标签和复选框),Vue将自动返回一组选定值。

如何将v模型添加到自定义组件 (How to add v-model to custom components)

To let our component support v-model two-way binding, the component needs to accept a value prop and emit an input event.

为了让我们的组件支持v-model双向绑定,组件需要接受一个value prop并发出一个input事件。

Let’s create a sample component called basic-input. We’ll use Vue’s single file component:

让我们创建一个称为basic-input的示例组件。 我们将使用Vue的单个文件组件 :

<template>
  <input @input="handleInput" />
</template>

<script>
export default {
  prop: ['value'],
  data () {
    return {
      content: this.value
    }
  },
  methods: {
    handleInput (e) {
      this.$emit('input', this.content)
    }
  }
}
</script>

To support v-model, the component accepts a value prop and emits an input event.

为了支持v-model ,组件接受一个value prop并发出一个input事件。

Use the component like this:

使用这样的组件:

<basic-input v-model="email" />

自定义v模型道具和事件 (Customizing v-model prop and event)

Let’s take it a step further. We might not want to use the default event and prop needed to add v-model support to our components. Thankfully, Vue allows us to customize it.

让我们更进一步。 我们可能不想使用向组件添加v-model支持所需的默认事件和prop。 幸运的是,Vue允许我们对其进行自定义。

To customize the event and prop, we add a model property to our component and define the new values like this:

为了自定义事件和道具,我们向组件添加model属性并定义新值,如下所示:

export default {
  prop: ['hidden'],
  model: {
      prop: 'hidden',
      event: 'blur'
  }
  methods: {
      handleInput (value) {
          this.$emit('blur', value)
      }
  }
}

This time, when you use the component like this:

这次,当您使用这样的组件时:

<basic-input v-model="email" />

Vue will automatically convert it into:

Vue会自动将其转换为:

<basic-input :hidden="email" @blur="e => email = e.target.value" />

With this in place, you can avoid conflicts when defining your component’s prop and events.

有了这个,您就可以避免在定义组件的prop和事件时发生冲突。

在ContentEditable上使用v模型 (Using v-model on ContentEditable)

A content editable element is a div or similar element that can be configured to work as an input.

内容可编辑元素是div或类似元素,可以将其配置为用作输入。

We define content editable elements by adding the contenteditable attribute to the element:

我们通过将contenteditable属性添加到元素来定义内容可编辑元素:

<div class="editor" contenteditable="contenteditable"></div>

You’ll use content editable elements for WYSIWYG editors as they are easier to work with and are supported by a large amount of browsers.

您将为所见即所得(WYSIWYG)编辑器使用内容可编辑的元素,因为它们易于使用并且受到大量浏览器的支持 。

v-model will work on content editable elements, but you need to explicitly use the content of the element, or the content will not be emitted.

v-model将对内容可编辑元素起作用,但是您需要显式使用元素的内容,否则将不会发出内容。

To emit the content, you need to grab the innerText or innerHTML of the div. So, our updateInput method needs to look like this

要发出内容,您需要获取divinnerTextinnerHTML 。 因此,我们的updateInput方法需要看起来像这样

updateInput () {
  this.$emit('input', this.$el.innerText)
}

You can also use the content of a ref instead of the root element’s content.

您还可以使用ref的内容而不是根元素的内容。

With this in place, v-model will work for content editable elements. You could also update this.content in the updateInput method.

有了这个, v-model将适用于内容可编辑元素。 您也可以在updateInput方法中更新this.content

结论 (Conclusion)

Now that you have seen how to use v-model with custom Vue components, go build or refactor your components that require the use of v-model.

既然您已经了解了如何将v-model与自定义Vue组件一起使用,请构建或重构需要使用v-model

翻译自: https://www.digitalocean.com/community/tutorials/how-to-add-v-model-support-to-custom-vue-js-components


http://www.niftyadmin.cn/n/3649139.html

相关文章

mongodb启动失败[转]

现象&#xff1a; 查看日志的内容如下 Tue Jan 4 09:51:37 MongoDB starting : pid2794 port27017 dbpath/var/lib/mongodb 32-bit ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data ** see http://blog.mongodb.org/post/137788967/…

Android的各种Drawable讲解

Android把可绘制的对象抽象为Drawable&#xff0c;不同的图形图像资源就代表着不同的drawable类型。Android FrameWork提供了一些具体的Drawable实现&#xff0c;通常在代码中都不会直接接触Drawable的实现类。在实际的开发过程中&#xff0c;会把使用到的资源都放置在res/draw…

使用黑盒测试在 Go 中重写 Bash 脚本

目录 前言&#xff1a; 开始 准备工作 描述行为&#xff1a;Bats 简介 行为描述&#xff1a;陷阱 描述行为&#xff1a;设计测试 重写&#xff1a;让我们开始用go吧&#xff01; 重构和更新&#xff1a;实现胜利 结论 前言&#xff1a; 使用黑盒测试在Go中重写Bash脚本…

Ormlite的工具使用

配置 compile com.j256.ormlite:ormlite-android:5.0 使用 常用注解 DatabaseTable(tableName "t_user") 指定实体和表的一一对应关系 DatabaseField() 指定属性与表中列的一一对应关系 常用配置说明&#xff1a; 主键&#xff1a;id true 自增主键&#xff1a;gen…

如何在Ubuntu 18.04上使用Ansible使用LAMP安装和设置WordPress

介绍 (Introduction) Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of aut…

Windows文本框星号密码查看器

Windows文本框星号密码查看器本人2002的学习作品作者&#xff1a;成晓旭1、 设计原理&#xff1a;注册一个系统级鼠标挂钩&#xff0c;通过监测系统鼠标所在Windows窗口来获取密码&#xff0c;成功获取密码之后&#xff0c;通过发送自定义的Windows系统消息&#xff0c;到宿主…

Celery 链接RabbitMQ报错CRITICAL/MainProcess] Frequent restarts detected: RestartFreqExceeded('5 in 1s',)

为了别人&#xff0c;也是为了将来自己忘了&#xff0c;备忘一个问题 在实现Celery链接RabbitMQ的时候&#xff0c;感觉万事具备了&#xff0c;却报错&#xff1a; CRITICAL/MainProcess] Frequent restarts detected: RestartFreqExceeded(5 in 1s,) raceback (most recent ca…

简单使用style实现沉浸式状态栏

我之前也写过一个沉浸式的文章&#xff1a;http://blog.csdn.net/qq_24675479/article/details/78557698 今天写一个比较简单点的&#xff1a; 默认情况下的style&#xff1a; <resources><!-- Base application theme. --><style name"AppTheme" p…