1.安装vuex
$ yarn add vuex 或者$npm i vuex -S
2.在src目录下创建store目录在store.js文件下:
import Vuex from ‘vuex‘
import Vue from ‘vue‘
import * as todos from ‘../pages/vuex_basic/store‘
Vue.use( Vuex )
const store = new Vuex.Store({
modules: {
//每一个分块出去的数据包
vue_basic: {
state: todos.state,
actions: todos.actions,
mutations: todos.mutations,
getters: todos.getters
}
}
})
export default store
3.在main.js中注册:
import store from ‘./store‘
new Vue({
store, // 在项目中注入store,让所有的子组件拥有一个属性 $store , 用于和vuex进行通信
render: h => h(App),
}).$mount(‘#app‘)
4.创建 vue_basic/store.js,打造 state actions mutations getters
import axios from ‘axios‘
const ADD_TODOS = ‘addTodos‘
const GET_CATEGORY = ‘getCategory‘
export const state = {
todos: [
{
id: 1,
task: ‘任务一‘
},
{
id: 2,
task: ‘任务二‘
}
],
category: null
}
export const actions = {
addTodos ({ commit }, val ) {
const action = {
type: ADD_TODOS,
val
}
commit( action )
},
getCategory ( {commit} ) {
axios({
url: ‘/index.php‘,
params: {
r: ‘class/category‘,
type: 1
}
}).then( res => {
// 动作创建
const action = {
type: GET_CATEGORY,
payload: res.data.data.data
}
commit( action )
}).catch( error => console.log( error ))
}
}
export const mutations = {
[ ADD_TODOS ] ( state,action ) {
state.todos.push({
id: state.todos.length + 1,
task: action.val
})
},
[ GET_CATEGORY ] ( state,action ) {
state.category = action.payload
}
}
export const getters = {
getTodos ( state ) {
return state.todos
}
}
5.在 vue_basic/index.vue使用:
<template>
<div>
<h3> vuex - 数据分块 - todolist增加功能 </h3>
<input type="text" v-model = "val" @keyup.enter="add">
<ul>
<li v-for = "item in todos" :key = "item.id">
{{ item.task }}
</li>
</ul>
<button @click = "getCategory"> 点击获取数据 </button>
<ul>
<li v-for =‘item in category‘ :key = "item.cid">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
import { mapState,mapActions } from ‘vuex‘
export default {
data () {
return {
val: ‘‘
}
},
methods: {
...mapActions([‘addTodos‘,‘getCategory‘]), // 容易忘记
add () {
this.addTodos( this.val )
this.val = ‘‘
}
},
computed: {
...mapState({
todos: state => state.vue_basic.todos, // 这里是一个箭头函数来取数据
category: state => state.vue_basic.category
})
}
}
</script>
原文:https://www.cnblogs.com/zjp-com/p/11455994.html