vuex store的運用

來源:互聯網
上載者:User

vuex用來管理vue的所有組件狀態。
首先下載vuex,”vuex”:”^3.0.1”,運用”vuex-persistedstate”來對資料進行緩衝。下載”vuex-persistedstate”
在檔案中引入:(建立一個store檔案夾,在檔案夾下的index.js檔案進行如下編寫)

import Vue from 'vue'import Vuex from 'vuex'import createPersistedState from 'vuex-persistedstate'Vue.use(Vuex)

定義簡單模組:

const module = {    state: {        user: {            name: 'rookie'        }    },    getters: {},    mutations: {        setUser(state, payload){            if(payload.hasOwnProperty('name')){                state.user.name = payload.name            }        }    },    plugins: [createPersistedState()]}

上面是一個簡單的vuex,在vuex中對應的store應用,在store中包含組件的共用狀態state和改變狀態的方法(暫且稱作方法)mutations。注意state相當於對外的唯讀狀態,不能通過store.state.user.name來更改,使用store.commit方法通過觸發mutations改變state。
在頁面中擷取記錄的值name為rookie:

mounted(){    console.log(this.$store.state.user.name);}

store.state為擷取store中的值,此時在my頁面中列印出來的值為rookie,而我們想要修改name的值,則需要藉助store.commit方法來觸發mutations:

this.$store.commit('setUser',{name: 'kuke_kuke'})

在mutations中找到setUser,第二個參數payload為傳入的對象{name: ‘kuke_kuke’},調用方法hadOwnProperty來判斷傳入的對象是否有name屬性,從而修改state中的值,此時在頁面中再次列印user.name的值為’kuke _ kuke’。
最後匯出模組:

const store = new Vuex.Store(module)export default store

別忘記在main.js中擷取模組並使用:

import store from './store'new Vue({    store})

作者:rookie.he(kuke_kuke)
部落格連結:http://blog.csdn.net/qq_33599109
歡迎關注支援,謝謝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.