Vue

Vue 组件通信方法 — vuex

2020-08-05  本文已影响0人  Qingelin

组件通信的原理在 Vue 两种组件通信方法 中已经讲解过了,本篇文章中主要介绍vuex的原理和用法。


1. 什么是vuex

vuex是专为vue.js项目开发的集中式存储管理所有组件的状态,并以一种可预测的状态发生变化,简单来说就是这个vuex状态机里面写好了vue项目可能发生的所有信息,任何组件都可以访问它,它会按规则发生通知,使得相应的组件发生预定状态的变化。

如图所示:

2.使用vuex的好处

3. vuex 用法

Vue.use(Vuex)    //使用vuex
//创建一个store实例
const store = new Vuex.Store({
  state: {  //声明state状态树
    count: 0,
    firstName: "qing",
    lastName: "lin"
  },
  mutations: {    //mutation中提交需要改变的方法
    increment(state) {   //mutation中触发一个increment的mutation时调用此函数(state作为第一个参数),*注意,不同于action,mutation必须是同步函数
      state.count++
    }
  },
  getters:{
    fulleName(state){
        return state.firstName + " " + state.lastName
    }
  }
})


const Counter = {
//页面中渲染出state状态树中的内容
  template: '
<div>
    <div>{{count}}</div>
    <p>{{firstName}}{{lastName}}</p>
    <button @click="add">+</button>
</div>',  //这里的state,firstName,lastName都是从computed计算属性中获取的
  computed: {
      count() {
         return this.$store.state.count  //computed计算属性中的state是从store实例中获取的,这个的是响应式的,只要有一个变化,页面中的state也会跟着变化
        },
        //fullName(){
          // return this.$store.getters.fullName
        //},
          //这两种写法作用一样,建议使用下面的写法
        ...Vuex.mapGetters(["fullName"]),
        ...Vuex.mapState(['firstName', 'lastName'])  ,  //展开运算符,推荐使用这种写法,以新对象替换老对象
     },  
    methods:{
        add(){   //调用方法
            this.$store.commit('increment')
        }
    }
}



const app = new Vue({
  el: "#app",
  store,  //把store的实例注入到所有子组件中
  components: {
    Counter
  },
  template: '<div class="app"><counter></counter></div>'
})

store.commit('increment')  //在根节点中注入store
  const store = new Vuex.Store({
      state:{
          count:0;
      } ,
      mutations:{
        increment(state){
            state.count ++
        }
      },
      //action不会直接修改store实例,而是通过提交mutation的方法间接地修改store
      action:{
          commit(context){ //这里的context可以看做是store,但不完全是,所以这个参数也可以是store实例中的方法
              context.commit("increment")
          }
      }
  })

上一篇 下一篇

猜你喜欢

热点阅读