9、vuex快速上手

vue脚手架

npm install -g vue-cli

usage:

vue init

example:

vue init webpack myvue

安装vuex:

npm i -S vuex

详情看官网:
https://vuex.vuejs.org/zh/guide/

使用main.js 引入store,注册实例store

import Vue from 'vue'
import App from './App'
import router from './router'
import store from "./store";

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

src中创建store文件夹,文件夹中创建index.js

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

Vue.use(Vuex);

let store = new Vuex.Store({
	state:{
		msg:'vuex测试文件',
		todos: [
			{ id: 1, text: '...', done: true },
			{ id: 2, text: '...', done: false }
	    ]
	},
	getters:{
		doneTodos: state => {
			console.log(23333)
	      	return state.todos.filter(todo => todo.done)
	    }
	},
	mutations:{
		changeMutation(state,payload){
            //state.msg = "vuex测试文件change";
            state.msg = payload.tmp;
            console.log(123,state.msg,payload)//{tmp:"vuex测试文件change"}
        },
	},
	actions:{
		changeAction({commit},payload){
            commit("changeMutation",{tmp:"vuex测试文件change"});
            console.log(123,payload)//undefined
        },
	},
	modules:{},
})

export default store;


components文件夹中的About.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>

    <h2 @click='change({tmp:"vuex测试文件change"})' >vuex-test</h2>
    <div>{{this.$store.state.msg}}</div>
  </div>
</template>

<script>
import Vue from 'vue';
import {mapActions,mapMutations,mapState,mapGetters} from "vuex";

export default {
  name: 'About',
  data () {
    return {
      msg: 'Hellow world'
    }
  },
  methods:{
    test(){
       //console.log(1,this.$route.params);
      //console.log(2,this.$route.query.name);
      //console.log(3,this.$store.state.msg)
      //console.log(this.msg)
     // console.log(this.$store.getters.doneTodos)

    },
    //change({tmp:"vuex测试文件change"})中的参数映射到changeAction({commit},payload){}中的payload
    ...mapActions({change:"changeAction"}),
    //...getActions()

  },
  computed:{
    ...mapState({
    //设置state的msg值为store的state.msg
      msg2: state => state.msg
    }),
    //...mapGetters({rename:"doneTodos"}),
    ...mapGetters(["doneTodos"]),
   
  },
  updated(){
    this.test();
    //this.rename;
    this.doneTodos
  },
  mounted(){
    //this.test();
    
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

</style>


Module

Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
原文地址:https://www.cnblogs.com/zhongchao666/p/9680290.html