I encountered a problem in the project, and now three files are created to mainly represent it.
There is a constructor file calc.js
// Calc.js
function Calc (){
this.a = 1;
this.b = 2;
}
Calc.prototype.setA = function(argument){
this.a = argument;
};
Calc.prototype.setB = function(argument){
this.b = argument;
};
Calc.prototype.calc = function(){
console.log(this.a, this.b);
return this.a * this.b;
};
module.exports = Calc;
There is a component file calc.vue
<!-- calc.vue -->
<template>
<p id="calc">
<input type="text" v-model='a' />
<input type="text" v-model='b' />
<span>{{c}}</span>
</p>
</template>
<script>
import Calc from '../../static/js/calc.js'
let calc = new Calc();
export default {
name: 'calc',
data(){
return {
a: 1,
b: 2,
c: 4,
}
},
created(){
this.c = calc.calc();
},
watch: {
a(newV){
calc.setA(newV);
this.c = calc.calc();
},
b(newV){
calc.setB(newV);
this.c = calc.calc();
}
}
}
</script>
The last is the main file, referencing 2 calc.vue components
<template>
<p id="app">
<calc /> // 第一个
<hr>
<calc /> // 第二个
</p>
</template>
<script>
import calc from './components/calc.vue'
export default {
name: 'app',
components: {
calc
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
The interface is as follows
I changed the b of the second calc.vue component to 8
Then change the a of the first calc.vue component to 10
The main problem now is that I first modified b of the second component, and then modified a of the first component, and the result became 80
There are 2 components but 2 instances of calc.js are not generated. Why? How to deal with it
To change
v-model
to something different, try usingprops
?