Vue JS - 如何为按钮绑定一个值然后单击将值保存到本地存储

Vue JS - How to bind a value for a button then on click save the value to local storage

我有三个按钮,我想制作它以便我可以 select 这些按钮之一,然后当我单击名为 的按钮时保存到本地存储, selected 按钮的值保存在本地存储中,我使用存储按钮文本和值的对象,如

{ btnText: "Green", value: "green-value" }

这是我的完整代码

<template>
  <div>
    <div>
      <div v-for="(i, index) in buttonsGroup" :key="index">
        <button
          :class="{
            EthnicityActive:
              i === EthnicityActive && 'EthnicityActive-' + index,
          }"
          v-on:click="EthnicityActive = i"
        >
          {{ i.btnText }}
        </button>
      </div>
    </div>

    <div class="save">
      <button @click="save">Save to local storage</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      buttonsGroup: [
        { btnText: "Green", value: "green-value" },
        { btnText: "Blue", value: "blue-value" },
        { btnText: "Orange", value: "orange-value" },
      ],
      Save: null,
      EthnicityActive: "",
    };
  },
  methods: {
    save() {},
  },
};
</script>

到这里我想一切都清楚了,我创建了一个对象,然后我用了v-for,我有按钮,还有一个Save To Local Storage按钮,为了在我之后将它保存到本地存储select点击这三个按钮之一

您还可以看到给定的code in codesandbox

现在是时候完成您的方法了保存, 像下面几行:

save() {
  window.localStorage.setItem('keyName', this.EthnicityActive.value);
}

到目前为止你的代码很棒,只需在你的保存方法中添加:

save() {
  localStorage.setItem('selectedBtn',JSON.stringify(this.EthnicityActive))
  
},

它获取 EthnicityActive 的值(选定的 btn)并将对象存储到本地存储。

这是将您选择的按钮值存储到本地存储的代码 这是 2 个变化

  1. 将您的 EthnicityActive 设置为一个对象。 EthnicityActive: {} 由于您发送的是按钮对象,因此应该将 EthnicityActive 初始化为 empty object i.e {} 而不是 string i.e ''
  2. 点击保存可以存储localStorage.setItem(this.EthnicityActive.value)

这是修改后的代码

export default {
  data() {
    return {
      buttonsGroup: [
        { btnText: "Green", value: "green-value" },
        { btnText: "Blue", value: "blue-value" },
        { btnText: "Orange", value: "orange-value" },
      ],
      Save: null,
      EthnicityActive: {},
    };
  },
  methods: {
    save() {
      localStorage.setItem(this.EthnicityActive.value)
    },
  },
};

更新您的 save() 方法添加 restore() 方法,然后调用 restore() 在创建的挂钩上恢复您保存的数据。

methods: {
    save() {
      localStorage.setItem(
        "EthnicityActive",
        JSON.stringify(this.EthnicityActive)
      );
    },
    restore() {
      this.EthnicityActive = JSON.parse(
        localStorage.getItem("EthnicityActive")
      );
    },
  },
created() {
    this.restore();
  },

https://codesandbox.io/s/icy-frost-osdql?file=/src/components/HelloWorld.vue