vuex全局状态管理

2020-04-30  本文已影响0人  最念倾城
vuex.png

===
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
===
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
===

先建立一个文件夹store,在建立index.js文件

//创建全局状态管理实例
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let store = new Vuex.Store({
  //...
  state:{
    name:'韩梅梅',
    age:19
  },
  getters:{},
  //修改全局状态值
  mutations:{
    changeName(state,params){
      console.log('修改名字',state,params);
      state.name = params.name
      
    },
    changeAge(state,params){
      console.log('修改名字',state,params);
      state.age = params.pass
      
    }
  },
  actions:{}



})


export default store

===然后建立要写的项目
box,son1,son2
box

<template>
  <div>
    这里是Box组件
    <son1/>
    name:{{this.$store.state.name}}
    <hr/>
    <son2/>
   
  </div>
</template>

<script>
import son1 from './Son1'
import son2 from './Son2'

export default {
  components:{son1,son2},
  name:'Box',
  mounted() {
    console.log(this.$store.state.name)
  },

}
</script>

son1

<template>
  <div>
    <p>这里是son1组件</p>
    age{{this.$store.state.age}}
    <button @click="changee">改年龄</button>
  </div>
</template>

<script>
export default {
  mounted(){
    console.log('组件2',this)
  },
  methods: {
    changee(){
      //通过commit控制mutation
      this.$store.commit('changeAge',{name:123,pass:456})      
    }
  },
}
</script>

son2

<template>
  <div>
    <p>这里是son2组件</p>
      name:{{this.$store.state.name}}
      <button @click="change">改名</button>
  </div>
</template>

<script>
export default {
  mounted(){
    // console.log('组件2',this)
  },
  methods: {
    change(){
      //通过commit方法触发mutation
      this.$store.commit('changeName',{name:123,pass:456})
    }
  },
}
</script>
上一篇 下一篇

猜你喜欢

热点阅读