我们前面做了一个这样的页面,为了增加我们的学习难度,我们特意拆分成了不同的组件。
我们知道,我们在子组件里并不能直接对兄弟组件里的属性进行操作,我们通过this.$emit()
调用父组件的方法,通过this.$parent.$data.username
获取兄弟组件里的属性。
但是如果我们的业务越来越复杂,组件越来越多,会造成我们的整个项目维护起来非常的困难。
能不能把各个组件的逻辑,数据源和方法整合到一个地方?
Vuex是什么?
http://vuex.vuejs.org/zh-cn/intro.html
如果无法理解,你可以理解为一种开发模式或框架。比如PHP有thinkphp,java有spring等。
通过状态(数据源)集中管理驱动组件的变化(好比spring的IOC容器对bean进行集中管理)
vuex是以插件的方式存在的。
安装;
---
它必须以插件的方式进行引用:
import Vuex from 'vuex';Vue.use(Vuex);
vuex里面有什么?
应用级的状态集中放在store中;
改变状态的方式是提交mutations,这是个同步的事物;
异步逻辑应该封装在action中。
const vuex_store = new Vuex.store({ state:{ xxx:oooo; }})
演练
1、jssrc/index.js
里
import Vuex from 'vuex';Vue.use(Vuex);const vuex_store = new Vuex.Store({ state:{ user_name:"" }, mutations:{ showUserName(state){ alert(state.user_name); } }})
let myvue = new Vue({ el:".container", store:vuex_store, router:routerConfig,});
不要忘记需要注入到Vue实例。
2、在user-name.vue
组件里我们之前是通过this.$emit("childChange","username",this.username)
调用方法传递值的变化,现在我们需要修改成这样:this.$store.state.user_name = this.username;
完整的user-name.vue
代码如下:
<template> <div class="form-group"> <label class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username"> </div> </div></template><script> export default{ props:["placeholder"], data:function () { return { username:"" } }, methods:{ userNameChange(){ this.$store.state.user_name = this.username; } } }</script>
3、当点击提交按钮时候,弹出用户名
user-submit.vue
:
<template> <div class="form-group"> <div class="col-sm-10 col-sm-offset-2"> <button type="button" v-on:click="submit" class="btn btn-default">提交</button> </div> </div></template><script> export default{ methods:{ submit(){ this.$store.commit("showUserName"); } } }</script>
转载地址:http://blog.csdn.net/github_26672553/article/details/53176778