簡單的vuex 的使用案例筆記
1、 npm install vuex
2、 在src 下 新建文件夾 store (為什么是這個單詞,vuex 是用來狀態(tài)管理的,用儲存一些組件的狀態(tài),取存貯,倉庫之意),store 文件下 新建文件 index.js (為什么是index.js? 在導(dǎo)入的時候,會第一選擇這個叫index的文件)
3、 index.js import 導(dǎo)入 vue 和vuex (import 是es6 的語法, es5 是 require), 代碼如下:
這里的demo 是一個 改變 app 的模式 的一個appellation ,選擇是 夜間模式還是白天模式
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
night: true,
text: '白天',
className: 'morning'
},
mutations: {
increment (state) {
state.night = !state.night;
state.text = state.night === true ? '晚上' : '白天';
state.className = state.night === true ? 'night' : 'morning';
}
}
})
4、 main.js import 這個index.js 代碼如下:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store' // 會找index.js
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, // 注入根組件,其他子組件 都可以引用
template: '<App/>',
components: { App }
})
5、使用vuex 的狀態(tài)
組件1:
dom :
<div class="header" :class="model">
js
computed: {
model() {
return this.$store.state.className // 是ninght 還是 morning
}
},
注意:
:class="model" 這個class 可以綁定一個方法傳參數(shù),可以直接用 js 表達式,可以綁定一個計算屬性
組件2:
dom:
<div class='modal' @click="changeModel">
<div class="avatar">
<img src="../../assets/img/logo.png" width="18" height="18">
</div>
<div class="name">
{{currentModel}}
</div>
<!-- vuex 相當(dāng)于全局注入 vuex 然后取這里面的值 -->
</div>
js:
computed: {
currentModel () {
return this.$store.state.text
}
},
methods: {
changeModel () {
// document.body.className='night'
this.$store.commit('increment')
}
}
注意:
js 中的 currentModel 和 dom 中的 {{ currentModel }} 是一個,和 :class 可以跟表達方法一樣 ,可以跟變量 ,表達方法 ,表達式 ( 這里靈活的模版方法,回頭查看下源碼,然后補充這的說明, vue模版為何如此強大?。?/p>
點擊事件,觸發(fā)方法 changeModel ,changeModel 觸發(fā) mutation 的方法,顯示改變 值 ,這個是固定的語法, this.$store.commit('increment');
increment 可以在定義的時候,設(shè)置參數(shù),傳參數(shù), this.$store.commit('increment', 'argumnet') , 在 mutation 里面 increment (state , arg) { .. = arg; ....};
截圖如下:

默認方式:
如上圖顯示。默認的是,白天的模式,className 是 morning;
點擊事件觸發(fā)模式;

再次點擊的時候,可以在改回來,這個竅門,就是 index.js 里面,increment 對 night 的變量 取 對 的一個邏輯方法。跟jq 里面的 toggle,類似

結(jié)束語:
簡單的vuex 的案例 ,做個筆記。希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue學(xué)習(xí)-VueRouter路由基礎(chǔ)
這篇文章主要介紹了Vue學(xué)習(xí)-VueRouter路由基礎(chǔ),路由本質(zhì)上就是超鏈接,xiamian?文章圍繞VueRouter路由的相關(guān)資料展開詳細內(nèi)容,需要的小伙伴可以參考一下,希望對你的學(xué)習(xí)有所幫助2021-12-12
vue全局引入公共的scss和@mixin與@include的使用方式
這篇文章主要介紹了vue全局引入公共的scss和@mixin與@include的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
Vue創(chuàng)建淺層響應(yīng)式數(shù)據(jù)的實例詳解
這篇文章主要介紹了Vue創(chuàng)建淺層響應(yīng)式數(shù)據(jù)的實例,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11

