vuex operational flow - [data block]

1. Install vuex

$ Yarn add vuex or $ npm i vuex -S

2. Create store directory under the src directory store.js under file :

import Vuex from 'vuex'

Import view from 'View'

import * as todos from '../pages/vuex_basic/store'

Vue.use( Vuex )

const store = new Vuex.Store({

modules: {

// block out each packet

vue_basic: {

state: todos.state,

actions: todos.actions,

mutations: todos.mutations,

getters: todos.getters

}

}

})

export default store

3. In main.js registration :

import store from './store'

new view ({

store, // inject store in the project, so that all sub-components have a property $ store, for communication and vuex

render: h => h(App),

}).$mount('#app')

4. Create vue_basic / store.js , build state actions mutations getters

import axios from 'axios'

const ADD_TODOS = 'addTodos'

const GET_CATEGORY = 'getCategory'

export const state = {

everyone: [

{

id: 1,

task: ' task a '

},

{

id: 2,

task: ' Task II '

}

],

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 => {

// actions created

 

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. In vue_basic / index.vue use:

<template>

<div>

<h3> vuex - Data Block - todolist increased functionality </ 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"> Click for data </ 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']), // easy to forget

add () {

this.addTodos( this.val )

this.val = ''

}

},

computed: {

...mapState({

todos: state => state.vue_basic.todos, // this is a function to fetch arrow

category: state => state.vue_basic.category

})

}

}

</script>

 

Guess you like

Origin www.cnblogs.com/zjp-com/p/11455994.html