码迷,mamicode.com
首页 > Web开发 > 详细

JS——vuex 基本使用

时间:2018-07-07 20:07:13      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:outer   使用   get   method   route   vuex   router   仓库   ons   

父子组件通信是传递私有数据,非父子组件通信传递的是共享数据,对共享数据进行管理可以帮助我们对全局状态进行统一管理

vuex 安装

npm install vuex --save

vuex 挂载

import Vuex from ‘vuex‘
Vue.use(Vuex)

store 创建

var store = new Vuex.Store(
    state : {
        count : 0
    },
    mutations:{
    
    }
)

加载到 vue 实例

new Vue({
    el : ‘#app‘,
    router,
    components : {
        App
    },
    template : ‘<App/>‘,
    store
})

访问 store 数据

<span>组件1:</span><input type=‘text‘ v-model=‘$store.state.count‘>

改变 store 数据

直接操作 $store.state.count 是不被推荐的,store 提供了一个操作 count 值的接口 motations

// 仓库中定义方法,方法的第一个参数永远是state,类似过滤器
var store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add(state) {
      state.count++
    }
  }
})
// 组件通过commit方法进行调用
export default {
  methods: {
    add() {
      this.$store.commit("add");
    }
  }
};

调用接口并传参

commit 方法可以使组件改变共享数据,同时也可以传入参数,但是限制只能传入一个自己自定义的参数,所以在传入参数数据量大的情况下推荐使用对象传参

// 形式如下
this.$store.commit("add", obj)

store 过滤器

这种叫法不准确,但是在形式上,store 提供的 getters 接口最后在结果上确实很像过滤器

var store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add(state) {
      state.count++
    },
    remove(state, num) {
      state.count = state.count - (num.one + num.two)
    }
  },
  getters: {
    show(state) {
      return "加工一下 state 数据:" + state.count
    }
  }
})

需要注意的是,getters 接口在也很类似于 computed,因为 state 的值只要发生变化,就会触发 getters 方法

JS——vuex 基本使用

标签:outer   使用   get   method   route   vuex   router   仓库   ons   

原文地址:https://www.cnblogs.com/cnloop/p/9277809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!