vue项目笔记(21)-vuex代码优化

vuex代码优化

在使用vuex的项目代码中,html中往往会出现{{this.$store.state.city}}这种代码,很不规范。vuex中给出了部分api可以对此进行优化。

mapState

home/compoments/Header.vue中{{this.$store.state.city}}修改为{{this.city}},引入mapState,并设置计算属性。

    <router-link to="/city">
      <div class="header-right">
        {{this.city}}
        <span class="iconfont arrow-icon">&#xe6aa;</span>
      </div>
    </router-link>
import { mapState } from 'vuex' // 引入

computed:{
      ...mapState(['city']) // 添加computed
    }

其中,...是展开符,将vuex中state中的city映射到该组件中,对应的计算属性也是city,mapState可以接受数组或对象。

mapMutations

city/components/List.vue中,我们做如下修改:首先,引入mapMutations,而后在methods中使用mapMutations,映射changeCity方法,然后在点击事件中调用该方法,注意:传入参数city。

  import { mapState, mapMutations } from 'vuex'
    methods: {
      handleCityClick(city){
//        this.$store.commit('changeCity', city); 此段代码有以下代码代替
        this.changeCity(city);
        this.$router.push('/');
      },
      ...mapMutations(['changeCity'])
    }

猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/81734854