zoukankan      html  css  js  c++  java
  • VUE 直接通过JS 修改html对象的值导致没有更新到数据中去

    业务场景

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

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

    原因分析

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

    解决办法

    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 控件,我们在使用这个控件的时候。

    <rx-textarea   @myfocus="getTextarea" v-model="item.sql"></rx-textarea>

    编写一个 getTextarea 的方法。

    var curTextarea=null;
            function  getTextarea(e){
                curTextarea= e.target;
            }

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

    function insertPK(){
                $.insertText(curTextarea,"{pk}")
            }

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

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

  • 相关阅读:
    【R】爬虫案例
    [R] 保存pheatmap图片对象到文件
    [R] 添加误差棒的分组折线图:geom_path: Each group consists of only one observation. Do you need to adjust the...
    [R] read.table/read.delim读入数据行数变少?
    [R] cbind和filter函数的坑
    [R]在dplyr函数的基础上编写函数(3)tidyeval
    [R]在dplyr基础上编写函数(2)substitute和quote
    30个Java知识点
    Java的30个知识点
    40个知识点
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/11695916.html
Copyright © 2011-2022 走看看