Vuex速学篇:(1)基本套路
来源:互联网 发布:jenkins windows节点 编辑:程序博客网 时间:2024/05/07 20:16
我们前面做了一个这样的页面,为了增加我们的学习难度,我们特意拆分成了不同的组件。
我们知道,我们在子组件里并不能直接对兄弟组件里的属性进行操作,我们通过this.$emit()
调用父组件的方法,通过this.$parent.$data.username
获取兄弟组件里的属性。
但是如果我们的业务越来越复杂,组件越来越多,会造成我们的整个项目维护起来非常的困难。
能不能把各个组件的逻辑,数据源和方法整合到一个地方?
Vuex是什么?
http://vuex.vuejs.org/zh-cn/intro.html
如果无法理解,你可以理解为一种开发模式或框架。比如PHP有thinkphp,java有spring等。
通过状态(数据源)集中管理驱动组件的变化(好比spring的IOC容器对bean进行集中管理)
vuex是以插件的方式存在的。
安装;
npm install vuex --save-dev
它必须以插件的方式进行引用:
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, //注入到vue 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.$emit("childChange","username",this.username) 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(){ //alert(this.$parent.$data.username +"==="+ this.$parent.$data.userarea); this.$store.commit("showUserName"); } } }</script>
1 0
- Vuex速学篇:(1)基本套路
- Vuex速学篇:(1)基本套路
- Vuex速学篇:基本套路
- Vuex的基本使用
- struts基本套路
- google play基本套路
- Spring Security 基本套路
- NOIP Dp基本套路大全
- vuex
- vuex
- vuex
- Vuex
- vuex
- vuex
- vuex
- vuex
- vuex
- Vuex
- Oracle11g bbed install and example
- DNA序列
- emmet用法
- 2016普级组模拟试题(20161114) 平台
- NOIP2016提高A组集训第16场11.15 总结
- Vuex速学篇:(1)基本套路
- HTML常用标签整理(k类)
- 第k大的数
- Lisp实现多义线闭合
- leetcode oj java Find All Anagrams in a String
- 3.1矩阵的构造
- POJ 2886 Who Gets the Most Candies? [线段树-单点更新]【数据结构】
- 利用ASH功能定位处理产生core文件超大问题
- 安卓着色器Tint的使用