【问题标题】:How to initialize a vue property with javascript variable如何使用 javascript 变量初始化 vue 属性
【发布时间】:2020-11-07 20:22:14
【问题描述】:

在第 19 行的这段代码中,我想将 document.body.getElementById('calculationid').value 传递给 vue 变量 (calcvalue),但它不起作用,所以我该如何解决它或者是否有任何其他解决方案来获取输入标签值.

<template>
  <div class="home">
 
    <input type="text" v-model="calcoperation" id="calculationid"  >

  </div>
</template>
<script>
export default{
  name:"home",
  data(){
    return{
     var calcvalue : document.body.getElementById('calculationid').value ,
      title: "",
      valuecalc: "",
      calcoperation: "" 
     // valuecalc: calcoperation
    };
  },
  methods:{
    //To contact the input field text with the button pressed
    contterms(str){
      var temp = "" + str  
      
      this.calcoperation = this.calcoperation + temp
    }
  }, 
  mounted(){
    fetch("http://localhost:8085")
      .then(response =>{
        return response.text();
      })
      .then(data =>{
        this.title=data;
      });
  }
};
</script>

【问题讨论】:

    标签: javascript html vue.js vuejs2


    【解决方案1】:

    不要以这种方式操作 DOM,您可以将 calcvalue 声明为空变量,然后通过观看 calcoperation 或将其定义为计算属性来更新它:

    data(){
        return{
         calcvalue : "" ,
          title: "",
          valuecalc: "",
          calcoperation: "" 
         // valuecalc: calcoperation
        }
    },
    watch:{
       calcoperation(newVal,oldVal){
        this.calcvalue=newVal
       }
    
    }
    

    【讨论】:

    • 通过这个你将 v-model 设置为这个观察者?? @Boussadjra
    • 你的输入仍然绑定到calcoperation,就像&lt;input type="text" v-model="calcoperation" id="calculationid" &gt;一样,观察者只是查看变化并执行适当的逻辑,如this.calcvalue=newVal
    • 不,这会引发错误,因为您已经定义了 v-model
    • 输入已经绑定到calcoperation,您可以按照我的建议修改calcvalue,可以更详细地说明您的实际需求
    • calcoperation 是双向绑定到输入的,输入的任何变化都会影响calcoperation,反之亦然
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2011-12-03
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多