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

20 篇文章 0 订阅
17 篇文章 0 订阅

安装依赖

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值