Vue Directive 数据绑定如 v-model

问题描述 投票:0回答:1

使用

v-model
可以将响应式对象的属性绑定到 html 组件

<input v-model="myObject.property" />

但是,当我将

myObject.property
绑定到我的自定义指令时:

<input v-customDirective="myObject.property" />

可以通过

binding.value
访问该值 - 并且该值不是反应性的

我试图找出他们如何在 vue 中做到这一点 - 但我没有成功。如何实现像数据绑定这样的v模型?

更新:

我对

myObject.property
功能进行了
updated(el, binding, vnode, prevVnode)
更改。但我想要

directives: {
  'custom-input': {
     created(el, binding) {
        el.value = binding.value;
        el.addEventListener('input', () => {
           // ---- this does not work ------
           binding.value = el.value;
        });
     },
     updated(el, binding) {
        console.log('Value has updated', binding.value);
     }
  },

},

vuejs3 v-model
1个回答
0
投票

使用此语法无法实现您想要的效果,因为

myObject.property
已展开并作为值传递给指令,并且您无法更改 JS 中按值传递的任何变量。

此外

myObject.property
字符串在运行时不可用,您无法猜测指令值的来源。

最接近您想要的可以通过提供绑定到对象属性的引用来完成:

游乐场

<script setup>
import { reactive , toRef } from 'vue'

const myObject= reactive({property: 'Hello World!'});

const vCustomDirective = (el, {value})=>{
  el.value = value.value;
  el.addEventListener('input', e => value.value = el.value);
}

</script>

<template>
  <h1>{{ myObject }}</h1>
  <input v-customDirective="toRef(myObject, 'property')" />
</template>
© www.soinside.com 2019 - 2024. All rights reserved.