vue项目中使用vuex管理公共状态1-vuex同步(state和mutations)

vuex 网站: https://vuex.vuejs.org/zh/guide/

vuex是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能 (这句话来至官网)
在这里插入图片描述

在使用vue-cli创建项目时选中Vuex的话就不用在进行安装了
在这里插入图片描述
项目目录里的 store 目录就是编写vuex的地方

state

定义

store目录下的index.js中:

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

Vue.use(Vuex)

export default new Vuex.Store({
    
    
  // stire 定义 '全局 状态'
  state: {
    
    
    cityId: 310100,
    cityName: '上海'
  },
  // 集中式修改状态,
  mutations: {
    
    
  },
  actions: {
    
    
  },
  modules: {
    
    
  }
})

在项目中使用

<div>
	{
   
   { $store.state.cityName }}
</div>
<!--使用 {
    
    {}} 语法时不写 this-->

<script>

export default {
     
     
  mounted () {
     
     
    console.log(this.$store.state.cityName)
  }
}
</script>

mutations

  • 在这里集中式修改state内的值

定义

store目录下的index.js中:

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

Vue.use(Vuex)

export default new Vuex.Store({
    
    
  // stire '全局 状态'
  state: {
    
    
    cityId: 310100,
    cityName: '上海'
  },
  // 集中式修改状态,
  mutations: {
    
    
    changeCityId (state, item) {
    
    
      // console.log(item)
      state.cityId = item
    },
    changeCityName (state, item) {
    
    
      // console.log(item)
      state.cityName = item
    }
  },
  actions: {
    
    
  },
  modules: {
    
    
  }
})

使用

<div>
	{
   
   { $store.state.cityName }}
	<button  @click="handleChangeCity">点击修改:</button>
</div>
<!--使用 {
    
    {}} 语法时不写 this-->

<script>

export default {
     
     
  data () {
     
     
    return {
     
     
      name: 北京,
      id: 1111111
    }
  },
  mounted () {
     
     
    console.log('全局状态',this.$store.state.cityName)
  },
  methods: {
     
     
    handleChangeCity () {
     
     
      // 修改公共状态
      // cityId, cityName
      // this.$store.state.cityName = this.name // 这样也可以修改, 不过这样修改不会被记录
      // 记录修改的记录
      this.$store.commit('changeCityId', this.name)
      this.$store.commit('changeCityName', this.id)
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/lxb_wyf/article/details/113607033