0

The code is as below:

<el-input v-model="ruleForm.vol" @change="calValue(vol,ruleForm.vol)">
  <template slot="suffix">{{ vol }}</template>
</el-input>

data() {
  return {
    vol: 0,
    ruleForm: {
       vol: 0
    }      
  }
},
methods: {
  calValue(objCal, obj) {
    console.log(objCal)
    console.log(eval(obj))
    objCal = eval(obj)
    console.log(objCal)
  }
}

When I type 1+1 in the input box, the suffix is not changed. How to solve it?

Ian
  • 354
  • 1
  • 5
  • 22

1 Answers1

2

Firstly (something you might already know, but...), avoid using eval in production, especially when user input plays a factor. This opens your app up to different security vulnerabilities, here namely script injection and cross-site scripting (read more about XSS).

Secondly, you're not setting a new value for vol here, hence it doesn't change. Inside your calValue method, make sure to set a new value for it.

<el-input v-model="ruleForm.vol" @change="calValue(vol, ruleForm.vol)">
  <template slot="suffix">{{ vol }}</template>
</el-input>

data() {
  return {
    vol: 0,
    ruleForm: {
       vol: 0
    }      
  }
},
methods: {
  calValue(objCal, obj) {
    console.log(objCal)
    console.log(eval(obj))
    objCal = eval(obj)
    this.vol = objCal
  }
}

(!) But an even better approach for this is to use Vue's computed properties. With those, your code would now look like:

<el-input v-model="vol">
  <template slot="suffix">{{ result }}</template>
</el-input>

data() {
  return {
    vol: 0
  }
},
computed: {
  result () {
    return eval(this.vol)
  }
}

Notice how you don't need a method and a @change listener, since v-model already changes the mapped value on every @input behind the scenes (more on this here).

Again - if you're building a calculator or something similar and wish to be aware of security, you'd probably parse the user input 1 + 1 into {argument} {operator} {argument} and then call a method based on the operator that the user used.

Hope this helps!

tony19
  • 125,647
  • 18
  • 229
  • 307
kano
  • 5,626
  • 3
  • 33
  • 48
  • great thx @Kano !!!, I'm new hand of Vue.js. Computed properties is the right solution. And u r right, there is security issue if user input unexpected value. I need to use regular expression to restrict the input format. Thanks again! – Ian Sep 11 '18 at 08:42