1、vuex的入门案例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="container"> <h1>{{$store.state.count}}</h1> <!--在界面上访问用的是$store进行访问,类似$router--> <bill></bill> </div> <template id="bill"> <div> <input type="button" value="add" @click="add"> <input type="button" value="del" @click="del"> </div> </template> <script src="./vue.js"></script> <script src="./vuex.js"></script> <script> //状态数据存储 let state = { count: 1 }; /** * 改变数据的方法集合 * @type {{add(*): void, del(*): void}} */ let mutations = { //注册到vuex后,在vue中访问需要用到this.$store.commit('name')方法进行访问 add(state) { state.count ++; }, del(state) { state.count --; console.log(this); //这里的this指向的是vuex的整个对象,从中也可以获取state数据 } }; let store = new Vuex.Store({state, mutations}); let bill = { template: '#bill', store, //绑定vuex methods: { add(){ this.$store.commit('add'); //触发mutations里的方法 }, del() { this.$store.commit('del'); } } }; let app = new Vue({ el: '#container', components: { bill }, store //绑定vuex }) </script> </body> </html>