以上是vuex的官方文檔對vuex的介紹,官方文檔對vuex的用法進行了詳細的說明。這里就不再細講vuex的各個用法,寫這篇博客的目的只是幫助部分同學(xué)更快地理解并上手vuex。
1. 安裝
$ npm install vuex --save
2. 在main.js 主入口js里面引用store.js
3. 在store.js里引用Vuex
4. 在vue組件中使用
使用$store.commit('jia')區(qū)觸發(fā)mutations下面的加減方法
<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{$store.state.count}}</h5> <p> <button @click="$store.commit('jia')">+</button> <button @click="$store.commit('jian')">-</button> </p> </p> </template> <!-- 加上scoped是css只在這個組件里面生效,為了不影響全局樣式 --> <style scoped> h5{ font-size: 20px; color: red; } </style>
5. 查看演示
6. state訪問狀態(tài)對象
使用computed計算
<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{count}}</h5> <p> <button @click="$store.commit('jia')">+</button> <button @click="$store.commit('jian')">-</button> </p> </p> </template> <script> import {mapState} from 'vuex' export default{ name:'hello', //寫上name的作用是,如果你頁面報錯了,他會提示你是那個頁面報的錯,很實用 // 方法一 // computed: { // count(){ // return this.$store.state.count + 6 // } // } // 方法二 需要引入外部 mapState computed:mapState({ count:state => state.count + 10 }) // ECMA5用法 // computed:mapState({ // count:function(state){ // return state.count // } // }) //方法三 // computed: mapState([ // 'count' // ]) } </script>
7. mutations觸發(fā)狀態(tài) (同步狀態(tài))
<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{count}}</h5> <p> <button @click="jia">+</button> <button @click="jian">-</button> </p> </p> </template> <script> import {mapState,mapMutations} from 'vuex' export default{ name:'hello', //寫上name的作用是,如果你頁面報錯了,他會提示你是那個頁面報的錯,很實用 //方法三 computed: mapState([ 'count' ]), methods:{ ...mapMutations([ 'jia', 'jian' ]) } } </script>
8. getters計算屬性
getter不能使用箭頭函數(shù),會改變this的指向
在store.js添加getters
9. actions (異步狀態(tài))
在store.js添加actions
在組件中使用
<template> <p class="hello"> <h1>Hello Vuex</h1> <h5>{{count}}</h5> <p> <button @click="jia">+</button> <button @click="jian">-</button> </p> <p> <button @click="jiaplus">+plus</button> <button @click="jianplus">-plus</button> </p> </p> </template> <script> import {mapState,mapMutations,mapGetters,mapActions} from 'vuex' export default{ name:'hello', computed: { ...mapState([ 'count' ]), ...mapGetters([ 'count' ]) }, methods:{ // 這里是數(shù)組的方式觸發(fā)方法 ...mapMutations([ 'jia', 'jian' ]), // 換一中方式觸發(fā)方法 用對象的方式 ...mapActions({ jiaplus: 'jiaplus', jianplus: 'jianplus' }) } } </script> <style scoped> h5{ font-size: 20px; color: red; } </style>
10. modules 模塊
適用于非常大的項目,且狀態(tài)很多的情況下使用,便于管理
修改store.js
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com