搜尋

首頁  >  問答  >  主體

javascript - 請問如何優化該vue組件?

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

因為v-if這些必須掛載到元素裡,雖然這樣能實現切換,但button歸屬元素覺得不規範.有什麼改進方法沒?

<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 是頁面標題,雖然這實現了預設載入標題和切換標題,但感覺代碼冗餘.有沒有簡單的辦法?

伊谢尔伦伊谢尔伦2837 天前474

全部回覆(1)我來回復

  • 伊谢尔伦

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

    目前想到的一個

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

    回覆
    0
  • 取消回覆