search

Home  >  Q&A  >  body text

javascript - How to optimize this vue component?

<template>
  <p>
    <ul>
      <li>帐号 <input type="text" name="user"></li>
      <li>密码 <input type="password" name="password"></li>
    </ul>
    <ul v-if="title == '用户注册'">
      <li>确认密码 <input type="password" name="password"></li>
      <li>邮箱 <input type="text" name="email"></li>
      <li>
        <input type="submit" value="注册">
        <input v-on:click='change' type="button" value="登录">
      </li>
    </ul>
    <ul v-else>
      <li>
        <input type="submit" value="登录">
        <input v-on:click='change' type="button" value="注册">
        忘记密码?
      </li>
    </ul>
  </p>
</template>

Because v-if must be mounted into the element, although this can achieve switching, the button attribute element feels irregular. Is there any improvement method?

<script>
export default{
  data () {
    return {
      title: '用户登录'
    }
  },
  methods: {
    change: function () {
      this.title = this.title === '用户登录' ? '用户注册' : '用户登录'
    }
  },
  watch: {
    title: function () {
      this.$store.commit('setValue', {title: this.title})
    }
  },
  created: function () {
    this.$store.commit('setValue', {title: this.title})
  }
}
</script>

title is the page title. Although this implements loading and switching titles by default, it feels like the code is redundant. Is there an easy way?

伊谢尔伦伊谢尔伦2756 days ago402

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:27:59

    The one that comes to mind right now

      methods: {
        change: function () {
          this.title = this.title === '用户登录' ? '用户注册' : '用户登录'
          this.$store.commit('setValue', {title: this.title})
          return this.title
        }
      },
      created: function () {
        this.change()
      }

    reply
    0
  • Cancelreply