一 创建测试项目
vue init webpack-simple vuedemo
二 进入demo目录
cd vuedemo
三 安装依赖
cnpm install
四 安装vuex
cnpm install vuex --save
五 修改代码
├── App.vue
├── components
│ ├── Content.vue
│ ├── Home.vue
│ ├── News.vue
│ ├── User
│ │ ├── AddUser.vue
│ │ └── UserList.vue
│ └── User.vue
├── main.js
├── router
│ └── router.js
└── vuex
└── store.js
App.vue
home
news
user
Content.vue
i am content
{{list.title}}
Home.vue
Home
{{this.$store.state.count}}
News.vue
News
-
{{k}} -- {{item.title}}
AddUser.vue
Add User
UserList.vue
User List
User.vue
-
Add User
-
User list
main.js
import Vue from 'vue'
import App from './App.vue'
import './assets/css/basic.scss'
import router from './router/router.js'
import VueResource from 'vue-resource'
Vue.use(VueResource)
new Vue({
el: '#app',
router,
render: h => h(App)
})
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Home from '../components/Home.vue'
import News from '../components/News.vue'
import Content from '../components/Content.vue'
import User from '../components/User.vue'
import AddUser from '../components/User/AddUser.vue'
import UserList from '../components/User/UserList.vue'
const routes = [
{path:'/home', component:Home},
{path:'/news', component:News},
{
path:'/user',
component:User,
children:[
{path:'adduser', component:AddUser},
{path:'userlist', component:UserList},
]
},
{path:'/content/:aid', component:Content},
{path:'*', redirect:''}
]
const router = new VueRouter({
routes
})
export default router;
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//data
var state = {
count:1
}
//function
var mutations={
incCount(){
++state.count;
}
}
const store = new Vuex.Store({
state,
mutations: mutations
})
export default store;
六 运行
npm run dev
七 总结
Vuex用于不是父子组件,也不是兄弟组件的传值。数据共享,数据持久化。可也用本地存储和session实现。
state 状态管理变量的表
mutations 修改状态变量的函数
《1 导入vuex,定义数据和状态
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//data
var state = {
count:1
}
//function
var mutations={
incCount(){
++state.count;
}
}
const store = new Vuex.Store({
state,
mutations: mutations
})
export default store;
《2 在页面使用,本地函数,调用vuex模块中的mutations函数
import store from '../vuex/store.js';
export default {
data(){
},
store, methods:{
incount(){
this.$store.commit('incCount');
}
}
}
《3 页面使用vuex中的变量
Home
{{this.$store.state.count}}
八 参考
https://vuex.vuejs.org/guide/