import Vue from "vue"; import Vuex from "vuex"; import axios from "axios"; Vue.use(Vuex); const store = new Vuex.store({ //配置项(vuex中5个属性,这里只说三个) //公共仓库,储存数据 state:{ n:10 }, //处理异步函数和业务逻辑,里面的参数都是函数 actions:{ }, //主要用来修改state中的数据 mutations:{ } }) export default store;
main.js: import store from "./store/"; new Vue({ el: ‘#app‘, router, store, components: { App }, template: ‘<App/>‘ }) //挂载完成后,vue实例中增加了$store,即可通过this.$store来访问store对象的各种属性和方法 这个可以拿到store中数据,就可以在组件中进行页面的渲染 {{this.$store.state.n}} //100
--->state--->components
二、vuex数据传递流程:
如果组件中想要修改state中数据的值: <template> <div class="hello"> <h2>home</h2> <h3>{{this.$store.state.n}}</h3> <button @click="handleClick()">修改</button> </div> </template> 你可能会想到在methods:{}中写handleClick函数修改,但这样是不行的。 原因:违反了vuex单向数据流的特点。 在当前组件中修改公共仓库state的值后,所有组件页面上的值都改变了, 如果程序出现错误,错误会无法捕获。 所以要遵循vuex的特点数据传递流程进行修改。
---> components--->actions methods:{ handleClick(){ this.$store.dispatch("handleAdd") //通过dispatch调用actions里的方法 } } actions:{ handleAdd(){ console.log("actions里的方法被调用了") } }
---> actions ---> mutations actions:{ handleAdd({commit}){ //这个参数是个对象,解构赋值拿到对象中的commit commit("handlMutationseAdd") //通过commit调用 mutations里的方法 } } mutations:{ handlMutationseAdd(state,params){ //vuex中state属性 params:commit触发时,传递过来的数据 console.log("mutations被调用了",params) state.n++; console.log(state.n) } } 到此组件修改state中的数据完成,点击一次修改按钮n加1 接着页面上的数据重新进行了渲染----符合了vuex的特点数据是响应式的
5、总结下vuex数据传输流程
原文:https://www.cnblogs.com/xixinhua/p/10420177.html