【问题标题】:VueJS v3, Vuex and Composition API and v-model on input fieldVueJS v3、Vuex 和 Composition API 以及输入字段上的 v-model
【发布时间】:2021-12-21 05:32:50
【问题描述】:

问题

我有一些从 Vuex 商店获取搜索查询的代码。我正在使用计算属性来获取搜索查询,然后将其绑定到输入字段的 v-model。我希望能够通过输入字段编辑/更改搜索词,然后提交新的搜索查询,然后执行新的搜索查询。

但是由于计算属性是“只读”,当我在输入字段中更改搜索查询时,它不会更新搜索查询,并导致警告:

vendor.js:16674 Write operation failed: computed value is readonly

问题

如何从 Vuex 获取搜索查询、填充输入字段、更改/更新它,然后提交更改后的查询?我试图为组合 API 找到一个 computed 设置器,但找不到。

有什么想法吗?还是我应该看看另一种方法?

下面是代码

<template>

  <form role="search"
      aria-label="Sitewide"
      @submit.prevent="submitSearch"
      autocomplete="off">

    <input type="text" v-model="searchQuery" />
    <button type="button" v-on:click="submitSearch">Search</button>

  </form>
</template>

<script>
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
   name: "ProductSearchBox",
   setup() {
      const store = useStore();
      const searchQuery = computed(() => store.getters["search/getFiltersSearchTerm"]);

      const submitSearch = () => {
        store.dispatch('search/performSearch', searchQuery);
      }

      return {
          searchQuery,
          submitSearch
      }
   }
}
</script>

【问题讨论】:

    标签: vue.js vuex vuejs3 vuex4


    【解决方案1】:

    这听起来更像是watch 的用例。

    const searchQuery = ref('');
    watch(
      () => store.getters["search/getFiltersSearchTerm"],
      (term) => searchQuery.value = term
    );
    

    【讨论】:

    • 你,我的朋友,是个天才。这完美无缺。谢谢
    【解决方案2】:

    您可以像这样为 v-model 使用计算属性:

    <template>
        <form role="search"
            aria-label="Sitewide"
            @submit.prevent="submitSearch"
            autocomplete="off">
    
            <input type="text" v-model="searchQuery" />
    
        </form>
    </template>
    
    <script>
    import { computed } from 'vue'
    import { useStore } from 'vuex'
    
    export default {
       name: "ProductSearchBox",
       setup() {
          const store = useStore();
          const searchQuery = computed({
             get: () => store.getters['search/getFiltersSearchTerm'],
             set: (newValue) => store.commit('search/yourMutation', newValue)
          });
          
          const submitSearch = () => {
            store.dispatch('search/performSearch', searchQuery);
          }
    
          return {
              searchQuery,
              submitSearch
          }
       }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2018-06-13
      • 2021-07-27
      • 1970-01-01
      • 2020-09-10
      • 2016-04-21
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      相关资源
      最近更新 更多