Vuethis.$store詳解

一、什麼是Vuethis.$store

Vuethis.$store是Vue.js提供的狀態管理模式,它可以讓我們在Vue.js應用中進行集中式狀態管理。Vuex將狀態抽取出來,單獨管理,以便於實現數據共享和數據維護。

二、Vuethis.$store的使用場景

Vuex通常用於大型單頁面應用(SPA),其中數據流比較複雜而且數據量比較大的應用。對於一些簡單的應用,單獨使用Vuethis.$store可能會使得應用過度複雜。

三、Vuethis.$store的核心概念

1、state

state是Vuethis.$store的數據中心,即包含多個屬性的對象。

state: {
    count: 0
}

2、mutation

mutation是Vuethis.$store中用於修改state的唯一途徑,它類似於事件,每個mutation都有一個字元串類型的事件類型和一個回調函數。

mutations: {
    increment(state) {
        state.count++
    }
}

3、getter

getter與state類似,也是一個函數,它用於獲取某些狀態的值並做出響應操作。

getters: {
    getCount: state => {
        return state.count
    }
}

4、action

actions是用於處理非同步操作的方法。其傳遞給mutations的是mutation的payload。

actions: {
    incrementAsync({ commit }, payload) {
        setTimeout(() => {
            commit('increment', payload)
        }, 1000)
    }
}

四、Vuethis.$store的使用方法

1、安裝Vuex

使用npm安裝Vuex或者直接引入CDN都可以。

npm install vuex --save

2、創建一個store

在Vue.js應用的入口文件(main.js)中引入Vue和Vuex並實例化store。

import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations:{
        increment (state) {
            state.count++
        }
    },
    getters: {
        getCount: state => {
            return state.count
        }
    },
    actions: {
        incrementAsync({ commit }, payload) {
            setTimeout(() => {
                commit('increment', payload)
            }, 1000)
        }
    }
})

new Vue({
  render: h => h(App),
  store: store
}).$mount("#app")

3、Vuethis.$store的使用

在具體的Vue組件中訪問Vuethis.$store可以用$store屬性。

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button v-on:click="add">增加</button>
  </div>
</template>

<script>
export default {
    name: 'About',
    computed: {
        count () {
            return this.$store.getters.getCount
        }
    },
    methods: {
        add () {
            this.$store.commit('increment')
        }
    }
}
</script>

五、Vuethis.$store的使用案例

下面是一個根據GitHub API獲取GitHub用戶信息並展示的案例。

1、Vuex store.js

import axios from 'axios'

export default new Vuex.Store({
  state: {
    user: null,
    repositories: [],
    followers: [],
    following: [],
    loading: false,
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setRepositories(state, repos) {
      state.repositories = repos
    },
    setFollowers(state, followers) {
      state.followers = followers
    },
    setFollowing(state, following) {
      state.following = following
    },
    setLoading(state, loading) {
      state.loading = loading
    },
  },
  actions: {
    async fetchUser({ commit }, username) {
      commit('setLoading', true)
      const { data: user } = await axios.get(`https://api.github.com/users/${username}`)
      commit('setUser', user)
      commit('setLoading', false)
    },
    async fetchRepositories({ commit }, username) {
      commit('setLoading', true)
      const { data: repos } = await axios.get(`https://api.github.com/users/${username}/repos`)
      commit('setRepositories', repos)
      commit('setLoading', false)
    },
    async fetchFollowers({ commit }, username) {
      commit('setLoading', true)
      const { data: followers } = await axios.get(`https://api.github.com/users/${username}/followers`)
      commit('setFollowers', followers)
      commit('setLoading', false)
    },
    async fetchFollowing({ commit }, username) {
      commit('setLoading', true)
      const { data: following } = await axios.get(`https://api.github.com/users/${username}/following`)
      commit('setFollowing', following)
      commit('setLoading', false)
    },
  },
  getters: {
    getUser(state) {
      return state.user
    },
    getRepositories(state) {
      return state.repositories
    },
    getFollowers(state) {
      return state.followers
    },
    getFollowing(state) {
      return state.following
    },
    getLoading(state) {
      return state.loading
    },
  }
})

2、App.vue

<template>
  <div id="app">
    <input type="text" v-model="username" placeholder="GitHub username" />
    <button v-on:click="getUserData">查詢</button>
    <div v-if="loading">Loading...</div>
    <div v-else-if="user">
      <h2>{{ user.login }}</h2>
      <p>{{ user.bio }}</p>
      <p>followers: {{ user.followers }}, following: {{ user.following }}, public repos: {{ user.public_repos }}</p>
    </div>
    <div v-if="loading">Loading...</div>
    <div v-else-if="repositories">
      <h3>Repositories</h3>
      <ul>
        <li v-for="repo in repositories" :key="repo.id">
          <a :href="repo.html_url" target="_blank">{{ repo.full_name }}</a>
        </li>
      </ul>
    </div>
    <div v-if="loading">Loading...</div>
    <div v-else-if="followers">
      <h3>Followers</h3>
      <ul>
        <li v-for="follower in followers" :key="follower.id">
          <a :href="follower.html_url" target="_blank">{{ follower.login }}</a>
        </li>
      </ul>
    </div>
    <div v-if="loading">Loading...</div>
    <div v-else-if="following">
      <h3>Following</h3>
      <ul>
        <li v-for="follow in following" :key="follow.id">
          <a :href="follow.html_url" target="_blank">{{ follow.login }}</a>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'App',
  data() {
    return {
      username: ''
    }
  },
  computed: {
    ...mapGetters(['getUser', 'getRepositories', 'getFollowers', 'getFollowing', 'getLoading']),
    user() {
      return this.getUser
    },
    repositories() {
      return this.getRepositories
    },
    followers() {
      return this.getFollowers
    },
    following() {
      return this.getFollowing
    },
    loading() {
      return this.getLoading
    },
  },
  methods: {
    ...mapActions(['fetchUser', 'fetchRepositories', 'fetchFollowers', 'fetchFollowing']),
    async getUserData() {
      this.$store.commit('setUser', null)
      this.$store.commit('setRepositories', [])
      this.$store.commit('setFollowers', [])
      this.$store.commit('setFollowing', [])

      const username = this.username
      await Promise.all([
        this.fetchUser(username),
        this.fetchRepositories(username),
        this.fetchFollowers(username),
        this.fetchFollowing(username)
      ])
    }
  }
}
</script>

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/198525.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-04 10:25
下一篇 2024-12-04 10:25

相關推薦

  • Linux sync詳解

    一、sync概述 sync是Linux中一個非常重要的命令,它可以將文件系統緩存中的內容,強制寫入磁碟中。在執行sync之前,所有的文件系統更新將不會立即寫入磁碟,而是先緩存在內存…

    編程 2025-04-25
  • 神經網路代碼詳解

    神經網路作為一種人工智慧技術,被廣泛應用於語音識別、圖像識別、自然語言處理等領域。而神經網路的模型編寫,離不開代碼。本文將從多個方面詳細闡述神經網路模型編寫的代碼技術。 一、神經網…

    編程 2025-04-25
  • 詳解eclipse設置

    一、安裝與基礎設置 1、下載eclipse並進行安裝。 2、打開eclipse,選擇對應的工作空間路徑。 File -> Switch Workspace -> [選擇…

    編程 2025-04-25
  • MPU6050工作原理詳解

    一、什麼是MPU6050 MPU6050是一種六軸慣性感測器,能夠同時測量加速度和角速度。它由三個感測器組成:一個三軸加速度計和一個三軸陀螺儀。這個組合提供了非常精細的姿態解算,其…

    編程 2025-04-25
  • nginx與apache應用開發詳解

    一、概述 nginx和apache都是常見的web伺服器。nginx是一個高性能的反向代理web伺服器,將負載均衡和緩存集成在了一起,可以動靜分離。apache是一個可擴展的web…

    編程 2025-04-25
  • Python安裝OS庫詳解

    一、OS簡介 OS庫是Python標準庫的一部分,它提供了跨平台的操作系統功能,使得Python可以進行文件操作、進程管理、環境變數讀取等系統級操作。 OS庫中包含了大量的文件和目…

    編程 2025-04-25
  • git config user.name的詳解

    一、為什麼要使用git config user.name? git是一個非常流行的分散式版本控制系統,很多程序員都會用到它。在使用git commit提交代碼時,需要記錄commi…

    編程 2025-04-25
  • Java BigDecimal 精度詳解

    一、基礎概念 Java BigDecimal 是一個用於高精度計算的類。普通的 double 或 float 類型只能精確表示有限的數字,而對於需要高精度計算的場景,BigDeci…

    編程 2025-04-25
  • Python輸入輸出詳解

    一、文件讀寫 Python中文件的讀寫操作是必不可少的基本技能之一。讀寫文件分別使用open()函數中的’r’和’w’參數,讀取文件…

    編程 2025-04-25
  • Linux修改文件名命令詳解

    在Linux系統中,修改文件名是一個很常見的操作。Linux提供了多種方式來修改文件名,這篇文章將介紹Linux修改文件名的詳細操作。 一、mv命令 mv命令是Linux下的常用命…

    編程 2025-04-25

發表回復

登錄後才能評論