【问题标题】:Bind a VueX store state value to an input (VueJS)将 VueX 存储状态值绑定到输入(VueJS)
【发布时间】:2020-09-09 08:18:18
【问题描述】:

我是 VueJS 的新手,我正在创建一个 VueJS 应用程序,您可以在其中获取有关 Github 用户的一些信息, (例如:https://api.github.com/users/versifiction

我用VueX创建了一个商店,但是我需要更新用户在输入中写入的值, 我的“inputValue”总是在“”(它的默认值),当我在输入中输入时,存储值仍然在“”

我试过这个: 输入.vue

<template>
  <div class="input">
    <input
      type="text"
      :placeholder="placeholder"
      v-model="inputValue"
      @change="setInputValue(inputValue)"
      @keyup.enter="getResult(inputValue)"
    />
    <input type="submit" @click="getResult(inputValue)" />
  </div>
</template>

<script>
import store from "../store";

export default {
  name: "Input",
  props: {
    placeholder: String,
  },
  computed: {
    inputValue: () => store.state.inputValue,
  },
  methods: {
    setInputValue: (payload) => {
      store.commit("setInputValue", payload);
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

还有这个: 存储/index.js

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    inputValue: "",
  },
  getters: {
    getInputValue(state) {
      return state.inputValue;
    }
  },
  mutations: {
    setInputValue(state, payload) {
      console.log("setInputValue");
      console.log("payload ", payload);
      state.inputValue = payload;
    },
  },
});

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

    根据 form handling 部分中的 vuex 文档,您应该这样做:

      :value="inputValue"
          @change="setInputValue"
    

     methods: {
        setInputValue: (event) => {
          store.commit("setInputValue", event.target.value);
        }
      }
    

    【讨论】:

    【解决方案2】:

    绑定 vuex 和组件的最简单和优雅的方法是使用计算属性。 上面的代码会变成,

     <input
          type="text"
          :placeholder="placeholder"
          v-model="inputValue"
          @keyup.enter="getResult(inputValue)"
        />
    

    在您的计算属性中,您需要将 inputValue 替换为以下代码。

    computed: {
        inputValue: {
          set(val){
            this.$store.commit(‘mutationName’, val)
          },
          get() {
            return this.$store.stateName
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2019-08-17
      • 2020-06-21
      • 2018-04-03
      • 2017-10-30
      相关资源
      最近更新 更多