vuex使用demo

2019-07-27  本文已影响0人  大脸猫_2e21

本文仅用于记录学习过程。
由于目前做的项目在公共数据的使用上要求比较低,一般的父子传值就可以解决掉大多数的传值问题。今天有兴趣看了下vuex文档,然后试做了一个小demo。

npm install vuex --save
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)



export default new vuex.Store({
  state: {
    city: '上海'
  },
  actions: {
    changeCity (ctx, val){
      console.log(val)  //val是dispatch派发传递过来的值
      console.log(ctx)  //ctx是上下文,必传
      ctx.commit('changeCity', val)
    }
  },
  mutations: {
    changeCity (state, val){
      console.log(state)  //state  必传
      console.log(val)  // 要更改的值
      state.city = val
    }
  }
})
import store from '/@store'
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
<!--父组件中引入子组件-->
<template>
  <div >
    <div style="margin:100px 0 0 100px">
      {{$store.state.city}}
    </div>
    <test1></test1>
  </div>
</template>

<script>
import test1 from '@/components/test1.vue'
export default {
  components:{
    test1,
  },
  created () {
    console.log(this.$store.state)
  }
}
</script>
<!--子组件-->
<template>
  <div style="margin:100px 0 0 100px;cursor:pointer">
    <div>这是子组件</div>
    <div @click="changeCityClick">{{$store.state.city}}</div>
  </div>
</template>

<script>
export default {
  data () {
    return {

    }
  },
  methods : {
    changeCityClick () {
      this.$store.dispatch('changeCity', '北京')
    }
  }
}
</script>
//父组件不变
<!--子组件-->
<template>
  <div style="margin:100px 0 0 100px;cursor:pointer">
    <div>这是子组件</div>
    <div @click="changeCityClick">{{$store.state.city}}</div>
  </div>
</template>

<script>
export default {
  data () {
    return {

    }
  },
  methods : {
    changeCityClick () {
      this.$store.commit('changeCity', '北京')  //由dispatch更改成为commit
    }
  }
}
</script>
//store里index.js的修改如下

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)

export default new vuex.Store({
  state: {
    city: '上海'
  },
//将之前的actions删除掉
  mutations: {
    changeCity (state, val){
      state.city = val
    }
  }
})
上一篇 下一篇

猜你喜欢

热点阅读