vue,vue-router,vux,統合

3302 ワード

詳細
vueインスタンスのインスタンス化時にrouter storeステータス管理を初期化します.routerをトリガして対応するコンポーネントをレンダリングし、コンポーネントコンポーネントの操作によって状態の変更を完了します.
jsスクリプトを先に導入



    


html




jsスクリプト


  	const Foo = { 
					 template: '
foo{{count1}}
', // 该组件的私有数据 data:function(){ return {count:10}; }, computed:{ done:function(){ return this.$store.getters.doneTodos; }, count1:function(){ return this.$store.state.count; } }, methods:{ increase:function(){ this.$store.commit("increase",4); } } } const Bar = { // 该组件的view template: '
bar{{count}}
', // 该组件的方法 methods:{ decrease:function(){ this.$store.commit("decrease"); } }, // 该组件的计算属性 computed:{ count:function(){ return this.$store.state.count; } } }; const Baz = { template: '
baz
'} // Vue.component('topic', { // template:"这是topic" // }) // 实例化路由 const router = new VueRouter({ mode: 'history', routes: [ { path: '/bar', name:"bar", component: Bar }, { path: '/foo', name:"foo", component: Foo }, { path: '/other', components: { default: Baz, a: Bar, b: Foo } } ] }) // 初始化store实例 var store=new Vuex.Store({ // 声明需要使用到的共享状态 state:{ todos:[ {id:1,done:true}, {id:2,done:false}, {id:3,done:true} ], count:0 }, // 可以理解为计算属性 getters:{ doneTodos:function(state){ return state.todos.filter(function(todo){ return todo.done; }) } }, // 定义事件 // 组件内部统一通过 this.$store.commit("increase",obj)来进行提交更改需求 mutations:{ increase(state,a,b){ console.log(state,a,b) state.count++; }, decrease:function(state){ console.log("count:"+state.count); state.count--; console.log("count:"+state.count); } } }) window.a=new Vue({ router:router,//绑定路由,传入router实例到vue 组件内部可以通过this.$router来访问路由对象 store:store//将实例化后的store绑定到根节点,则任意组件都可以通过this.$store来访问到store实例 }).$mount("#app");



测试:a.$router.push({name:'bar'})
a.$router.push({name:'foo'})


クリックしてfooコンポーネントの下でクリックするとstore.countが1になり、

ルートをbarの下に切り替えるとcountも1.これにより、効率的な管理が実現されます.