vue全家桶(4.2)

5.2、使用vuex重构上面代码

Vuex是什么?官方定义:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

Vuex的使用步骤: 1 安装Vuex

npm install vuex --save

2 在src目录下,新建store文件夹,在store文件夹下新建index.js文件

3 在index.js文件中输入以下代码

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

// 让vuex作为vue的插件来使用
Vue.use(Vuex)

// 创建一个容器
let store = new Vuex.Store()

// 把这个store实例导出 方便在vue中注入
export default store

4 把store实例注入到vue中,在main.js中引入store

import Vue from 'vue'
import App from './App'
import router from './router'
import '@/assets/style/index.css'
import store from '@/store/index'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

接下来我们需要去使用vuex管理状态了,步骤

1、设置一个共享数据,在store/index.js里进行操作

//创建一个容器
let store = new Vuex.Store({
  state: {
    goods_num: 0
  }
})

2、把这个状态映射到视图中, 在components/VuexShoppingCar.vue里面去操作

<template>
  <div class="page">
    <div class="goods">购物车一共有:<span>{{ num }}</span> 件商品</div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  computed: {
    num () {
      console.log(this.$store.state)
      return this.$store.state.goods_num
    }
  }
}
</script>

<style scoped>
.goods{
  background-color: green;
  width: 250px;
  padding: 16px;
  color: white;
}
.goods span{
  color: red
}
</style>

3、提交一个mutation,这个mutation类似于js中的事件,有事件类型和事件处理函数,我们在事件处理函数中去更改全局的goods_num, 以下是VuexGoodsItem组件中的代码

<script type="text/ecmascript-6">
export default {
  data () {
    return {
      num: 12
    }
  },
  components: {

  },
  methods: {
    increase () {
      this.num++
    },
    decrease () {
      this.num--
    },
    addCar () {
      this.$store.commit('changeCar', this.num)
    }
  }
}
</script>

4、在store里面去增加一个mutation, 在store/index.js里面操作

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

// 让vuex作为vue的插件来使用
Vue.use(Vuex)

// 创建一个容器
let store = new Vuex.Store({
  state: {
    goods_num: 0
  },
  mutations: {
    changeCar (state, num) {
      console.log(state)
      state.goods_num += num
    }
  }
})

// 把这个store实例导出 方便在vue中注入
export default store

注意: 在步骤3里面 this.$store.commit('changeCar', this.num) 这句中提交的changeCar,真正执行的逻辑在步骤4中,mutation设置的changeCar

螺钉课堂视频课程地址:http://edu.nodeing.com

猜你喜欢

转载自www.cnblogs.com/dadifeihong/p/12035836.html