vue踩坑笔记 十二.vue中引入vuex

安装依赖

npm i vuex -s

引入vuex

在src目录下新建一个store目录,分别创建以下文件
在这里插入图片描述
项目比较简单,建一个state文件,一个mutations文件就行,如果项目规模大还可以按需创建getters文件,actions文件等

mutations.js

export default {
  changeCity (state, val) {
    state.city = val
  }
}

state.js

export default {
  city:"北京"
}

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations
})

main.js

import store from '@/store'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

在组件内引入
在这里插入图片描述

在需要用到vuex的组件内写入

 methods: {
    /* ... */
    ...mapMutations(['changeCity'])
  },
  computed: {
  	/* ... */
    ...mapState(['city'])
  },

就可像正常调用data里的数据一样调用state
像调用methods里的方法一样调用mutations或actions

样例代码

<template>
   <div class='list' ref = "wrapper">
     <div @click = "handleHostCity">
      <div class = "area">
        <p>当前城市</p>
        <div class="btnList">
          <div class="btn">{{this.city}}</div>
        </div>
      </div>
      <div class = "area">
        <p>热门城市</p>
        <div class="btnList">
          <div :data-city = "item.name"  v-for = "item in hostCityList" :key = "item.id" class="btn">{{item.name}}</div>
        </div>
      </div>
      <div class = "area" v-for = "(cityArr,index) in cityList" :key = "index" >
        <p :ref="index">{{index}}</p>
        <div class="city-list">
          <div v-for = "(item) in cityArr" :key = "item.id"
               :data-city = "item.name" class="city-item">{{item.name}}</div>
        </div>
      </div>
     </div>
   </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapState, mapMutations} from 'vuex'

export default {
  props: {
    nowCity: String,
    hostCityList: Array,
    cityList: Object | Array,
    alphabetIndex: String
  },
  methods: {
    // 滚动到指定位置
    scrollTo () {
      // 获取指定的元素
      let ele = this.$refs[this.alphabetIndex][0]
      this.scroll.scrollToElement(ele)
    },
    // 点击某个城市时,切换当前城市,回到主页
    handleHostCity (e) {
      let data = e.target.dataset.city
      this.changeCity(data)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    ...mapState(['city'])
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper, { click: true })
  },
  watch: {
    alphabetIndex () {
      this.scrollTo()
    }
  }
}
</script>

<style lang = "less" scoped>
</style>

发布了81 篇原创文章 · 获赞 1 · 访问量 6987
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览