Ian
Ian

Reputation: 354

How to pass var obj to the method in Vue.js

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?

Upvotes: 0

Views: 78

Answers (1)

kano
kano

Reputation: 5920

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!

Upvotes: 2

Related Questions