suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Javascript – Konstruktor in Vue verwenden

Ich bin im Projekt auf ein Problem gestoßen und habe jetzt drei Dateien erstellt, um es hauptsächlich darzustellen.
Es gibt eine Konstruktordatei 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;

Es gibt eine Komponentendatei 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>

Die letzte ist die Hauptdatei, die auf zwei calc.vue-Komponenten verweist

<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>

Die Schnittstelle ist wie folgt

Ich habe das b der zweiten calc.vue-Komponente auf 8 geändert

Ändern Sie dann das a der ersten calc.vue-Komponente auf 10

Das Hauptproblem besteht nun darin, dass ich zuerst b der zweiten Komponente und dann a der ersten Komponente geändert habe und das Ergebnis 80 wurde

Es gibt 2 Komponenten, aber 2 Instanzen von calc.js werden nicht generiert. Warum? So lösen Sie

ringa_leeringa_lee2798 Tage vor1059

Antworte allen(1)Ich werde antworten

  • 淡淡烟草味

    淡淡烟草味2017-06-14 10:56:42

    要把v-model改成不一样,试试用props

    Antwort
    0
  • StornierenAntwort