分类 前端 下的文章

安装

npm install vuex --save

使用

新建一个vuex文件,以下为./store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let defaultCity = '上海'

export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  actions: {
    changeCity (ctx, city) {
      ctx.commit('changeCity', city)
    }
  },
  mutations: {
    changeCity (state, city) {
      state.city = city
    }
  }
})

ps:
state是一些需要共享的数据
actions(ctx, city)处理$store.dispatch(x)的请求,ctx代表上下文,city代表请求的数据
mutations(state, city) 处理actions中ctx的commit,state为数据结构,city为commit的数据

在main.js中引入store并注册

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

在组件模板中的调用

<div class="button">{{this.$store.state.city}}</div>

修改数据

handleCityClick (city) {
  this.$store.dispatch('changeCity', city)
  // 可跳过dispatch直接commit
  // this.$store.commit('changeCity', city)
  this.$store.commit('changeCity', city)
}

子组件可以使用 $emit 触发父组件的自定义事件

子组件

<template>
  <ul class="list">
    <li class="item" v-for="(item,key) of cities" :key="key" @click="handleLetterClick">{{key}}</li>
  </ul>
</template>

<script>
export default{
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    }
  }
}
</script>

父组件

<template>
  <div>
    <city-header></city-header>
    <city-search></city-search>
    <city-list :cities="cities" :letter="letter" :hot="hotCities"></city-list>
    <city-alphabet :cities="cities" @change="handleLetterChange"></city-alphabet>

  </div>
</template>

<script>
import axios from 'axios'
import CityHeader from './components/Header'
import CitySearch from './components/Search'
import CityList from './components/List'
import CityAlphabet from './components/Alphabet'
export default{
  name: 'City',
  components: {
    CityHeader,
    CitySearch,
    CityList,
    CityAlphabet
  },
  mounted () {
    this.getCityInfo()
  },
  data () {
    return {
      cities: {},
      hotCities: [],
      letter: ''
    }
  },
  methods: {
    getCityInfo () {
      axios.get('/api/city.json')
        .then(this.handleGetCityInfSucc)
    },
    handleGetCityInfSucc (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.cities = data.cities
        this.hotCities = data.hotCities
      }
    },
    handleLetterChange (letter) {
      this.letter = letter
    }
  }
}
</script>