Search code examples
vue.jsvue-componentvuexvue-router

How can I access programming class globally in vuejs


I want to declare a class like below

class Customer{
 constructor(){
    this.id;       
    this.name;
    this.email;
    this.username;       
    this.password;
   }
}

I want to create its instance in any component in vuejs like this

export default {
  name: 'TestCompotent',
  data()
  {
    return{
      MainCutomer: new Customer()      
    }
  },
}

Please advice me, how can I do that?


Solution

  • Here is a WORKING DEMO.

    /src/class/Customer.js:

    class Customer {
      constructor(id, name, email, username, password) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.username = username;
        this.password = password;
      }
    }
    
    export default Customer;
    

    /src/components/HelloWorld.vue:

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <h3>TEST PAGE</h3>
        <h5>Main Customer</h5>
        <ul>
          <li>ID: {{ MainCustomer.id }}</li>
          <li>Name: {{ MainCustomer.name }}</li>
          <li>Username: {{ MainCustomer.username }}</li>
          <li>E-mail: {{ MainCustomer.email }}</li>
        </ul>
      </div>
    </template>
    
    <script>
    import Customer from "./../class/Customer";
    
    export default {
      name: "HelloWorld",
      props: {
        msg: String,
      },
      data() {
        let MainCustomer = new Customer(
          1,
          "Tony",
          "[email protected]",
          "Tony007",
          "myPassword123"
        );
        return {
          MainCustomer: MainCustomer,
        };
      },
    };
    </script>