我是靠谱客的博主 动听大象,这篇文章主要介绍VUE 直接通过JS 修改html对象的值导致没有更新到数据中解决方法分析,现在分享给大家,希望可以做个参考。

本文实例讲述了VUE 直接通过JS 修改html对象的值导致没有更新到数据中解决方法。分享给大家供大家参考,具体如下:

业务场景

我们在使用vue 编写 代码时,我们有一个 多行文本框控件,希望在页面点击一个按钮 在 文本框焦点位置插入一个 {pk}的数据。

发现插入 这个数据后,这个数据并没有同步到 数据中,但是直接通过键盘输入,就可以改变数据。

原因分析

在通过 JS 修改控件的value 数据后,并没有触发到数据更新。

解决办法

复制代码", methods:{ change:function(e){ this.$emit('input', e.target.value); }, focus:function(e){ this.$emit('myfocus', e); } }, watch: { curVal: function (val, oldVal){ this.$emit('input', this.curVal); }, value :function(val,oldVal){ if(val!=oldVal){ this.curVal=this.value; } } } })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Vue.component('rx-textarea', { props: { value:[String,Number], cols: { type: Number, default: 60 }, rows: { type: Number, default: 4 } }, data() { return { curVal:this.value } }, template: "<div><textarea class='rx-textarea' v-model='curVal' @focus='focus(event)' :cols='cols' :rows='rows' @blur='change(event)' ></textarea></div>", methods:{ change:function(e){ this.$emit('input', e.target.value); }, focus:function(e){ this.$emit('myfocus', e); } }, watch: { curVal: function (val, oldVal){ this.$emit('input', this.curVal); }, value :function(val,oldVal){ if(val!=oldVal){ this.curVal=this.value; } } } })

当文本框获取焦点时,我们发布一个 myfocus 控件,我们在使用这个控件的时候。

复制代码
1
<rx-textarea @myfocus="getTextarea" v-model="item.sql"></rx-textarea>

编写一个 getTextarea 的方法。

复制代码
1
2
3
4
var curTextarea=null; function getTextarea(e){ curTextarea= e.target; }

这里将文本框控件,抛出来,我们可以通过 js代码修改这个控件的value。

复制代码
1
2
3
function insertPK(){ $.insertText(curTextarea,"{pk}") }

通过这个代码我们往焦点处插入我们的代码。

当文本框失去焦点时,将当前控件的值作为 input 事件进行发布,从而实现了数据的同步。

希望本文所述对大家vue.js程序设计有所帮助。

最后

以上就是动听大象最近收集整理的关于VUE 直接通过JS 修改html对象的值导致没有更新到数据中解决方法分析的全部内容,更多相关VUE内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(226)

评论列表共有 0 条评论

立即
投稿
返回
顶部