vuex操做流程 - 【 數據分塊 】

1.安裝vuexphp

$ yarn add vuex 或者$npm i vuex -Svue

2.在src目錄下建立store目錄在store.js文件下ios

import Vuex from 'vuex'vuex

import Vue from 'vue'npm

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

Vue.use( Vuex )app

const store = new Vuex.Store({函數

modules: {this

//每個分塊出去的數據包url

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>

相關文章
相關標籤/搜索