基于单击 vuejs 顺风更改按钮

时间:2021-06-23 17:19:21

标签: javascript vue.js tailwind-css

我根据自己的学习能力扩展了此代码。我知道我绝对可以缩短很多时间,但我正在努力学习和扩展我的前端经验。

所以我有下面的代码。当 localstorage 设置为 true/false 时,它​​会选择正确的 v-if/else 部分。现在,我需要做的是根据按钮点击设置本地存储。

实现这一目标的最佳方法是什么?

   <div v-if="privateChat == 'false'">
          <button type="button">
                        <a key="privateChat" href="#" class="bg-red-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
                            <ChatIcon class="h-6 w-6 text-white"/>
                            <span class="pt-2">Private Chat OFF</span>
                        </a>
                    </button>
          </div>
          <div v-else>
          <button type="button">
                        <a key="privateChat" href="#" class="bg-green-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
                            <ChatIcon class="h-6 w-6 text-white"/>
                            <span class="pt-2">Private Chat ON</span>
                        </a>
                    </button>
          </div>

<script>
export default {
  data() {
    return {
      privateChat: (localStorage.getItem("privateChat") === 'true') ? 'true' : 'false',
     }
   },
  methods: {
    clickPrivateChat (value) {
      this.privateChat = value === true ? "true" : "false";
      localStorage.setItem("privateChat", value);
    },
  setup() {
    const enabled = ref(privateChat)
    let value = localStorage.getItem("privateChat");
    let privateChat = (value === 'true');
    }
</script>

1 个答案:

答案 0 :(得分:1)

您可以进行多项改进...

  • 使用实际的真/假值而不是“真”、“假”字符串
  • DRY:您只需要一个按钮;使用 Vue 计算值来显示“ON”或“OFF”
  • 使用条件 :class 逻辑来应用 bg-green-900

脚本:

  data() {
        return {
            privateChat: (localStorage.getItem("privateChat") === true) ? true : false,
        }
    },
    computed: {
        onOrOff() {
            return this.privateChat  ? 'ON' : 'OFF'
        }
    },
    methods: {
        clickPrivateChat (value) {
          this.privateChat = !this.privateChat
          localStorage.setItem("privateChat", value)
        },
        setup() {
            const enabled = ref(privateChat)
            let value = localStorage.getItem("privateChat")
            let privateChat = (value === true)
        }
  },

标记:

 <div>
    <button type="button" @click="clickPrivateChat">
        <a key="privateChat" href="#" :class="privateChat?'bg-green-900':''" class="bg-red-900 text-gray-100 hover:bg-gray-800 hover:text-white group w-full p-3 rounded-md flex flex-col items-center text-xs font-medium">
            <span class="pt-2">Private Chat {{ onOrOff }}</span>
        </a>
    </button>
 </div> 

improved Vue approach