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 事件进行发布,从而实现了数据的同步。

  • 相关阅读:
    css text-transform 属性
    CSS3 @media编写响应式页面
    css :first child与:first-of-type的区别
    前端外语网站合集
    webpack配置自动添加CSS3前缀
    vue中extend/component/mixins/extends的区别
    js缓动函数
    [LeetCode] 78. 子集
    [LeetCode] 76. 最小覆盖子串
    [LeetCode] 75. 颜色分类
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/11695916.html
Copyright © 2011-2022 走看看