如何使用JavaScript变量初始化Vue属性

时间:2020-11-07 20:22:14

标签: javascript html vue.js vuejs2

在类似于第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>

1 个答案:

答案 0 :(得分:2)

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

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

}
相关问题