Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - How to use enums (or const) in VueJS?

I feel like an idiot for having to ask about something so seemingly simple, but I'm trying to figure out how to use "enums" in VueJS. Currently, in a file called LandingPage.js I have this bit of code:

const Form = {
  LOGIN: 0,
  SIGN_UP: 1,
  FORGOT_PASSWORD: 2,
};

function main() {
  new Vue({
    el: "#landing-page",
    components: {
      LoginForm,
      WhoIsBehindSection,
      WhatIsSection,
      Form,
    },
    data () {
      return {
        form: Form.LOGIN,
      };
    },
    template: `
    <div>
      <LoginForm v-if="form === Form.LOGIN"></LoginForm>
      <WhatIsSection></WhatIsSection>
      <WhoIsBehindSection></WhoIsBehindSection>
    </div>
    `
  });
}

It is the conditional v-if="form === Form.LOGIN" that is failing with the error messages:

  • Property or method "Form" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

  • Cannot read property 'LOGIN' of undefined

Just so you guys know without the conditional everything is working, and if I were to put this bit in the template

<p>{{ form }}</p>

it will print 0 on the screen. Though, putting this in the template

<p>{{ Form.LOGIN }}</p>

Will not result in it printing 0 on the screen. So I just cannot for the life of me figure out why it will not accept Form.LOGIN.

 

The Answer

I did add it to components, but never did I think of adding it to data. Happy that it's working now. :)

    data () {
      return {
        form: Form.LOGIN,
        Form, // I had to add this bit
      };
    },

Thank you MarcRo ??

question from:https://stackoverflow.com/questions/57538539/how-to-use-enums-or-const-in-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using Vue in Typescript, then you can use:

import { TernaryStatus } from '../enum/MyEnums';  

export default class MyClass extends Vue {

      myVariable: TernaryStatus = TernaryStatus.Started;

      TernaryStatus: any = TernaryStatus;  

 }

and then in Template you can just use

<div>Status: {{ myVariable == TernaryStatus.Started ? "Started It" : "Stopped it" }}</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...