【问题标题】:How to hide a paragraph using v-if through vuex?如何通过 vuex 使用 v-if 隐藏段落?
【发布时间】:2019-06-16 02:47:11
【问题描述】:

我正在尝试创建一个小应用程序,我可以在其中单击按钮并隐藏段落,但我正在尝试使用 vuex 来实现它。我的 Home.vue 文件中有一个段落,我的 About 中有一个按钮。 vue 文件。我希望在单击按钮时有条件地隐藏段落,但我想使用 vuex 来完成。我该怎么做?我的store.js、home.vue和About.vue如下。

This is how my store looks like.
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    show:true,
  },
  mutations: {
   toggle : state => {
     state.show = !state.show
   }
  },
  actions: {

  }
})

This is the Home.vue file
<template>
<p>This needs to disappear</p>
</template>

<script>
import {mapMutations} from "vuex"

export default {
 computed : {
   ...mapMutations ([
     "toggle"
   ])
 }
}
</script>

This is the About.vue file
<template>
  <div>
    <button @click="toggle">Click Me</button>
  </div>
</template>


<script>
import {mapMutations} from "vuex"

export default {
 computed : {
   ...mapMutations ([
     "toggle"
   ])
 }
}
</script>

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    mapMutations 应该用于不在计算属性中的方法中:

     methods:{
              ...mapMutations ([
                 "toggle"
               ])
      }
    

    就像你在official docs 看到的那样:

    您可以使用 this.$store.commit('xxx') 在组件中提交变更,或使用 mapMutations 助手将组件方法映射到 store.commit 调用(需要根存储注入):

    【讨论】:

    • 哦,是的,我明白了(我的错)。但是,我如何调整段落的状态,以便当我点击按钮时,段落应该隐藏?
    • 你可以做 &lt;p v-if="$store.state.show"&gt;This needs to disappear&lt;/p&gt; 或者在你的计算属性中使用 mapGetters
    • 哇,谢谢它的工作,但你能解释一下在模板中直接访问 $store 是如何工作的吗? vuex 会在每个组件中自动注入吗?
    • 因为你在像new Vue({el:"#app",store,data(){...},....})这样的vue实例中注入了store
    • 好吧,我明白了。太感谢了。你似乎总是在帮助我。感谢它兄弟
    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2023-03-23
    • 2021-09-17
    相关资源
    最近更新 更多