vue安装vuex框架
1.安装vuex
npm install vuex --save-dev
2.创建store
src下创建stores文件夹,创建noteStore.js
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); //vuex初始化 let note = new Vuex.Store({ state:{ //存储空间 items:[], name:'张三', say:'hello' }, mutations:{ //事件响应,修改存储的方法集 changeName:function(state,data){ state.name = data.name; }, changeSay:function(state,data){ state.say = data.say; }, changeItem:function(state,data){ state.items = data; } } }); export default note
3.创建action
创建actions文件夹,创建noteAction.js
import note from '../stores/note' export function changeName(id){ alert(id); //commit抛出事件,mutations中响应对应的事件changeItem note.commit('changeItem',[{id:1,name:'张三',say:'hello'},{id:2,name:'李四',say:'你好'},{id:3,name:'王五',say:'哈哈'}]); };
4.创建getter,获取事件方法
文件夹getdatas,创建noteGetter.js方法
import note from '../stores/note' export function getShow(vuea){ //默认传入所在的vue对象 //alert(note.state.name); return note.state.items; }
5.界面渲染
<template> <div id="app" class="app"> hello,note <table border='1' align='center'> <tr v-for="item in items"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.say}}</td> </tr> </table> <button @click='changeName'>改名</button> </div> </template> <script> import note from '../stores/note' import {getShow} from '../getdata/getter' import {changeName} from '../actions/Action' export default { computed:{ //items无须在data中声明,getShow传入的参数是this(vue对象) items:getShow }, methods:{ changeName:function(){ changeName(1); } } } </script>