Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

解决问题:

  • 传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。

  • 采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

参考文档:

  • https://github.com/vuejs/vuex/tree/dev/examples/shopping-cart
  • https://vuex.vuejs.org/zh-cn/getting-started.html

数据流动

开始

让我们做一个添加列表的功能

目录结构

 
├── index.css
├── index.js
├── store
│ ├── index.js
│ ├── main.js
│ └── modules
│ └── card.js
└── vue-mods
├── card.vue
└── index.vue
 

定义store.js

import Vue from 'vue'
import Vuex from 'vuex'

import card from "./modules/card.js";

//初始化store
export default new Vuex.Store({
//store的子模块
modules : {
card
},
//定义状态
state : {
msg : "hello, this msg is from vuex.store",
name : "zhangjian",
location : "zhengjiang"
},
//设置状态的获取,可以做一些特殊的定制
getters : {
detail : state => {
return state.msg + state.name
}
},
//mutation,用来修改state
mutations : {
CHANGE_LOCATION (state, location = "beijing"){
state.location = location;
}
},
//事件处理,主要是由外部触发store
actions : {
changeLocation ({ commit, state }){
commit("CHANGE_LOCATION");//触发mutation
},
changeLocationAsync ({commit, state}, {location}){
setTimeout(function (){
commit("CHANGE_LOCATION", location);
}, 1000);
}
}
});
 

modules/card.js ,和store.js和一致,只是输出的是一个模块

let state = {
list : [],
message : "this is card"
}

let getters = {

}

let mutations = {
ADD_CARD (state, card){
state.list.unshift(card)
},
UPDATE_MESSAGE (state, message){
state.message = message;
},
DELETE_CARD_BY_INDEX (state, index){
state.list.splice(index, 1);
}
}

let actions = {
addcard ({commit, state}, card){
let message = state.message;
let time = new Date().getTime();

commit("ADD_CARD", {name : `${message} card - ${time}`})
},
updateMessage ({commit, state}, message){
commit("UPDATE_MESSAGE", message);
},
deleteCard ({commit, state}, index){
commit("DELETE_CARD_BY_INDEX", index);
}
}

export default{
state, getters, mutations, actions
}

入口文件 App.vue

<style lang="less">
</style>
<template>
<div>
<p>{{msg}}</p>
<p>{{name}}</p>
<p>{{location}}</p>
<p>detail : {{detail}}</p>
<button @click="change">change location</button>
<button @click="asyncChange">async change location</button>
<card></card>
</div>
</template>
<script>
import store from "../store/";
import Card from "./card.vue";

export default {
components : {
Card
},
store,
created () {},
computed : {
msg (){
return "msg : " + this.$store.state.msg
},
name (){
return "name :" + this.$store.state.name
},
location (){
return "location :" + this.$store.state.location
},
detail (){
return this.$store.getters.detail
}
},
ready() {

},
methods : {
change (){
this.$store.dispatch("changeLocation")
},
asyncChange (){
this.$store.dispatch("changeLocationAsync", {
location : "china"
});
}
},
watch : {
},
filters: {
}
}
</script>

子模块 card.vue

<style lang="less">
</style>
<template>
<div>
<button @click="add">add card</button>
<input type="text" name="" @input="updateMessage" :value="message">
<span>{{cardCount}}</span>
<div v-for="(index, card) in list">{{card.name}}<span @click="del(index)">x</span></div>
</div>
</template>
<script>
export default {
components : {
},
computed : {
list (){
return this.$store.state.card.list
},
cardCount (){
return this.$store.state.card.list.length;
},
message (){
return this.$store.state.card.message
}
},
created () { },
ready() {

},
methods : {
add (){
this.$store.dispatch("addcard");
},
updateMessage (e){
this.$store.dispatch("updateMessage", e.target.value)
},
del (index){
this.$store.dispatch("deleteCard", index);
}
},
watch : {

},
filters: {
}
}
</script>

附上webpack.config.js

var webpack = require('webpack');
var vue = require('vue-loader')
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = {
//插件项
plugins: [
new ExtractTextPlugin("[name].css")
],
//页面入口文件配置
entry: {
index : './src/index.js'
},
//入口文件输出配置
output: {
path: './dist/',
filename: '[name].js'
},
module: {
//加载器配置
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract("css") },
{ test: /\.less$/, loader: ExtractTextPlugin.extract("css!less") },
{ test: /\.js$/, loader: "babel",query: {presets: ['es2015']},exclude: /node_modules/ },
{ test: /\.vue$/, loader: 'vue'}
]
},
vue : {
loaders: {
css: ExtractTextPlugin.extract("css"),
less: ExtractTextPlugin.extract("css!less")
},
autoprefixer: { browsers: ["ios_saf >= 7", "android >= 4"] }
},
externals: {
vue: "window.Vue",
vuex : "window.Vuex"
}
};

注意:这里,我针对vue和vuex2个仓库,做了一个全局引用,这样打包出来的boundle不会太大。

 

vue+vuex初入门的更多相关文章

  1. Vue+Vuex初体验

    首先: 安装vuex npm install vuex -S 需要有两个组件(HelloWord.vue 和 HelloDemo.vue)[组件自定义] 注册路由 注册store 测试 一.需要有两个 ...

  2. vue学习【四】vuex快速入门

    大家好,我是一叶,今天我们继续踩坑.今天的内容是vuex快速入门,页面传值不多的话,不建议vuex,直接props进行父子间传值就行,使用vuex就显得比较臃肿. 我们先预览一下效果,如图1所示. 图 ...

  3. Vue的简单入门

    Vue的简单入门 一.什么是Vue? vue.js也一个渐进式JavaScript框架,可以独立完成前后端分离式web项目 渐进式:vue可以从小到控制页面中的一个变量后到页面中一块内容再到整个页面, ...

  4. Vuex 2 入门与提高。

    从计数器开始 让我们从一个简单的计数器,开始进入Vuex 的世界: 计数器应用的数据模型很简单:使用一个counter属性来表示计数器的 当前值就够了. 在Vue实例的created钩子 中,应用启动 ...

  5. Vuex的入门教程

    前言 在 Vue.js 的项目中,如果项目结构简单, 父子组件之间的数据传递可以使用  props 或者 $emit 等方式,详细点击这篇文章查看. 但是如果是大型项目,很多时候都需要在子组件之间传递 ...

  6. vuex 基本入门和使用(三)-关于 mutation

    vuex 基本入门和使用(三)-关于 mutation vuex 版本为^2.3.1,按照我自己的理解来整理vuex. 关于 mutation 这里应该很好理解. 更改 Vuex 的 store 中的 ...

  7. vuex 初体验

    vuex是vue的状态管理工具,vue进阶从es6和npm开始,es6推荐阮一峰大神的教程. vuex学习从官方文档和一个记忆小游戏开始.本着兴趣为先的原则,我先去试玩了一把-->. Vuex ...

  8. 我的音乐盒子(nodejs7 + koa2 + vue + vuex + vue-router)

    你们知道的,nodejs对jser来说,是个好东西,快快的,自从接触nodejs后,总想弄点东西. 这弄个啥了,一天打开百度音乐盒,哟,自己弄一个如何了,好啊好啊. 后台: nodejs 7 + ko ...

  9. use vue vuex vue-router, not use webpack

    vue,vuex,vue-router放在一起能做什么?不用webpack之类的打包工具使用他们是否可行?各位道友在初学vue时是否有这样的困惑.因为现代构建前端项目的一般模式是: 安装webapck ...

随机推荐

  1. 用C++进行简单的文件I/O操作-转自VC知识库

    原文请见 http://www.vckbase.com/index.php/wv/1158 序论 我曾发表过文件输入输出的文章,现在觉得有必要再写一点.文件 I/O 在C++中比烤蛋糕简单多了. 在这 ...

  2. Content Negotiation(内容协商)

    Asp.Net Web API 2第十四课——Content Negotiation(内容协商)   前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http:// ...

  3. 历年noip复赛试题整合

    早晨打算把历年的试题都过一遍,整理一下大概会往哪个方向考,考什么,不说太多,开始吧 2013: Day1: T1 转圈游戏 : 快速幂(关键在于要会打 快速幂) 思路:因为每次都进m位,相当于每次x加 ...

  4. c# UDP/TCP协议简单实现(简单聊天工具)

    长时间没有摸这两个协议,写个代码温习下 下面是界面 [服务器界面] [登陆界面] [好友列表界面(我登陆了2个)] [聊天界面] 下面大致讲解下用到的内容 1.用户登陆于服务器通信用到的tcp协议,服 ...

  5. mac 下安装oh my zsh

    1.直接从github上下载 git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh  2.拷贝到账户目录下 cp ~/. ...

  6. cubie两种固定MAC地址的方法

    1.修改 /etc/init.d/networking 配置文件 在(a)代码的后面添加上(b)这段代码 (a)case "$1" in start) :5e #MAC地址可改 2 ...

  7. - 高级篇:二,IL设置静态属性,字段和类型转换

    - 高级篇:二,IL设置静态属性,字段和类型转换 静态属性赋值 先来看 Reflector反射出的IL源码(感谢Moen的提示),这次用 Release模式编译,去掉那些无用的辅助指令 public ...

  8. IP:网际协议

    IP:网际协议 1.概述      IP是TCP/IP协议族中最为核心的协议.所有的TCP,UDP,ICMP,IGMP数据都以IP数据报格式传输.      IP提供不可靠,无连接的数据报传送服务. ...

  9. DateTimePicker.Text不靠谱

    DateTimePicker.Text不靠谱 获取时:在DateTimePicker.ValueChanged事件中,获取到的Text有可能是string.Empty!!!,特别当ValueChang ...

  10. wireshark查看sip协议流

    选择中你要查看的sip消息-----右键--follow udp stream,就可以查看出消息流的整个流程.