vue,vue-router,vux,综合

实例化vue实例时初始化routerstore状态管理。触发router去渲染对应的组件,然后通过对组件组件的操作来完成状态的变更。

先引入js脚本

<scriptsrc="https://unpkg.com/vue/dist/vue.js"></script>

<scriptsrc="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<scriptsrc="https://unpkg.com/vuex@2.1.1"></script>

html
<div id="app">
	  <router-view ></router-view>
	</div>

js脚本

const Foo = { 
					 template: '<div v-on:click="increase">foo{{count1}}</div>',
					 // 该组件的私有数据
					 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: '<div v-on:click="decrease">bar{{count}}</div>',
					// 该组件的方法
					methods:{
						decrease:function(){
							this.$store.commit("decrease");
						}
					},
					// 该组件的计算属性
					computed:{
						count:function(){
							return this.$store.state.count;
						}
					}
				};
	const Baz = { template: '<div>baz</div>'}
	// Vue.component('topic', {
	// template:"<span>这是topic</span>"	
	// })
	// 实例化路由
	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.这样便实现了有效管理。

相关推荐