创建 单独文件 store.JS
- // 内部引用
- import vue from "vue"
- import Vuex from "vuex"
- Vue.use(Vuex)
模块化
- const store = new Vuex.Store({
- state,
- getters,
- actions,
- mutations
- })
state : 存放属性 如同 data
- const state = {
- lists : [
- {name : "cz", age : 20 },
- {name : "cz", age : 20 },
- ],
- count : 0
- }
getters : 获取数据 如同计算属性
- const getters = {
- cou : state => {
- return state.count
- },
- list : state => {
- var listFor = state.lists.map( a => {
- return {
- name : a.name,
- age : a.age
- }
- return listFor
- }
- }
- }
actions : 用户行为 如同 methods 方法 里面存用户改变时候的方法
- const actions = {
- // 加
- add({commit}){
- commit("muAdd") //
- },
- // 减
- cut({commit}){
- commit("muCut")
- },
- //list
- ageAdd({commit},num){
- commit("ageAdd",num)
- }
- }
mutations: 操作数据 在有用户行为后 操作数据改变数据
- const mutations = {
- muAdd: state => {
- state.count ++
- },
- muCut : state => {
- state.count --
- },
- ageAdd : (state,num) => {
- state.lists.forEach( element => {
- element.age += num
- })
- }
- }
最后 把 store 暴露出去 expore defult store
在 main.JS 中引用 store impore store from "./store.js"
在各个组件中如何调用 store 内的数据
通过 this.$store 方法获取 store 内的数据 $store 是 vuex 中的对象
在计算属性中直接 return 出想要的数据 如
- computed:{
- one(){
- return this.$store.state.lists
- }
- },
或者
先把 想要获取的数据通过 import { } from "vue" 导入到 当前组件
再通过 ...mapActions(['muAdd','muCut'])
来源: http://www.bubuko.com/infodetail-3145196.html