自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vuex原理:通過Vuex實(shí)現(xiàn)TodoList

開發(fā) 前端
「Vuex」 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它可以集中管理應(yīng)用中的組件共享狀態(tài),并提供一些工具來保持狀態(tài)的一致性。

什么是Vuex

「Vuex」 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它可以集中管理應(yīng)用中的組件共享狀態(tài),并提供一些工具來保持狀態(tài)的一致性。Vuex 主要用于解決以下問題:

  • 「組件通信」:在大型的 Vue.js 應(yīng)用中,多個(gè)組件可能需要共享一些狀態(tài)(數(shù)據(jù))。而通過簡單的組件通信方式(props、自定義事件)在復(fù)雜的組件關(guān)系中可能會(huì)變得不夠靈活或繁瑣。
  • 「狀態(tài)管理」:Vue.js 的單向數(shù)據(jù)流通過 props 將數(shù)據(jù)從父組件傳遞給子組件,但對(duì)于多層嵌套的組件結(jié)構(gòu),數(shù)據(jù)流管理可能變得復(fù)雜。Vuex 提供了一種集中式管理狀態(tài)的方式,使得狀態(tài)的變更變得可預(yù)測(cè)且易于調(diào)試。

以下是 Vuex 的核心概念:

1. 「State(狀態(tài))」

Vuex 使用一個(gè)包含應(yīng)用層級(jí)狀態(tài)的對(duì)象,即 State。這個(gè)狀態(tài)是響應(yīng)式的,當(dāng)狀態(tài)發(fā)生變化時(shí),相關(guān)組件將自動(dòng)更新。

const store = new Vuex.Store({
  state: {
    count: 0
  }
});

2. 「Mutations(變更)」

狀態(tài)的變更必須通過 Mutations 來進(jìn)行。Mutations 是同步函數(shù),用于修改狀態(tài)。通過這種方式,可以追蹤狀態(tài)的變更,并且可以實(shí)現(xiàn)一些限制條件,確保狀態(tài)的可控性。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

3. 「Actions(動(dòng)作)」

Actions 是用于提交 Mutations 的函數(shù),可以包含異步操作。通過 Actions,可以更靈活地處理業(yè)務(wù)邏輯,例如異步請(qǐng)求或條件判斷。

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

4. 「Getters(獲取器)」

Getters 允許組件在訪問狀態(tài)時(shí)進(jìn)行計(jì)算,類似于 Vue 組件中的計(jì)算屬性。Getters 的結(jié)果會(huì)被緩存,只有依賴的狀態(tài)發(fā)生變化時(shí)才會(huì)重新計(jì)算。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    doubleCount: state => state.count * 2
  }
});

5. 「Modules(模塊)」

Vuex 允許將 Store 分割成模塊,每個(gè)模塊擁有自己的 state、mutations、actions、getters。這樣可以更好地組織大型的 Store。

const moduleA = {
  state: { /* ... */ },
  mutations: { /* ... */ },
  actions: { /* ... */ },
  getters: { /* ... */ }
};


const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
});

6. 單一狀態(tài)樹

Vuex 使用一個(gè)單一的狀態(tài)樹來管理應(yīng)用中的所有狀態(tài)。這使得整個(gè)應(yīng)用的狀態(tài)變化可追蹤和調(diào)試。

7. Plugin(插件)

Vuex 允許通過插件擴(kuò)展其功能。插件是一個(gè)函數(shù),可以在每次 mutation 發(fā)生時(shí)執(zhí)行一些自定義的邏輯,例如記錄日志或持久化存儲(chǔ)。

// Vuex 插件示例
const myPlugin = store => {
  // 每次 mutation 時(shí)調(diào)用
  store.subscribe((mutation, state) => {
    console.log('mutation type:', mutation.type);
  });
};

8. 嚴(yán)格模式

Vuex 提供了嚴(yán)格模式,用于檢測(cè) State 的變更是否是通過 Mutations 進(jìn)行的。在開發(fā)環(huán)境中啟用嚴(yán)格模式可以幫助捕獲不合規(guī)的狀態(tài)變更。

const store = new Vuex.Store({
  // ...
  strict: process.env.NODE_ENV !== 'production'
});

通過這些概念,Vuex 提供了一種集中式狀態(tài)管理的解決方案,使得狀態(tài)在應(yīng)用中的傳遞和管理更為清晰和可維護(hù)。Vuex 不是必需的,尤其對(duì)于小型應(yīng)用可能會(huì)顯得繁瑣,但在大型、復(fù)雜的應(yīng)用中,它提供了一種有組織的方法來管理狀態(tài)。

利用Vuex實(shí)現(xiàn)一個(gè)tudoList

簡單了解一下Vuex之后呢,實(shí)現(xiàn)一個(gè)小案例。下面是一個(gè)使用 Vue 3 和 Vuex 的簡單的 Todo List 示例。使用前需要先下載依賴。這個(gè)應(yīng)該都會(huì)吧。創(chuàng)建一個(gè) store 文件夾,并在其中創(chuàng)建 index.js 文件來定義 Vuex 的 store:

// store/index.js
import { createStore } from 'vuex';


export default createStore({
  state: {
    todos: []
  },
  mutations: {
    addTodo(state, todo) {
      state.todos.push(todo);
    },
    toggleTodo(state, index) {
      state.todos[index].completed = !state.todos[index].completed;
    },
    removeTodo(state, index) {
      state.todos.splice(index, 1);
    }
  },
  actions: {
    addTodoAsync({ commit }, todo) {
      setTimeout(() => {
        commit('addTodo', todo);
      }, 1000);
    }
  },
  getters: {
    completedTodos: state => state.todos.filter(todo => todo.completed),
    remainingTodos: state => state.todos.filter(todo => !todo.completed)
  }
});

然后在 App.vue 文件中使用這個(gè) store:

// App.vue
<template>
  <div id="app">
    <h1>Todo List</h1>
    <form @submit.prevent="addTodo">
      <input v-model="newTodo" placeholder="Add a new todo" />
      <button type="submit">Add</button>
    </form>


    <div>
      <h2>Todo Items</h2>
      <ul>
        <li v-for="(todo, index) in todos" :key="index">
          <input type="checkbox" v-model="todo.completed" />
          {{ todo.text }}
          <button @click="removeTodo(index)">Remove</button>
        </li>
      </ul>
    </div>


    <div>
      <h2>Completed Todos</h2>
      <ul>
        <li v-for="(todo, index) in completedTodos" :key="index">
          {{ todo.text }}
        </li>
      </ul>
    </div>


    <div>
      <h2>Remaining Todos</h2>
      <ul>
        <li v-for="(todo, index) in remainingTodos" :key="index">
          {{ todo.text }}
        </li>
      </ul>
    </div>
  </div>
</template>


<script>
import { computed } from 'vue';
import { useStore } from 'vuex';


export default {
  name: 'App',
  data() {
    return {
      newTodo: ''
    };
  },
  methods: {
    addTodo() {
      this.$store.commit('addTodo', { text: this.newTodo, completed: false });
      this.newTodo = '';
    },
    removeTodo(index) {
      this.$store.commit('removeTodo', index);
    }
  },
  computed: {
    todos() {
      return this.$store.state.todos;
    },
    completedTodos: computed(() => useStore().getters.completedTodos),
    remainingTodos: computed(() => useStore().getters.remainingTodos)
  }
};
</script>


<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}


form {
  margin-bottom: 20px;
}


ul {
  list-style-type: none;
  padding: 0;
}


li {
  margin-bottom: 5px;
}
</style>

這個(gè)示例中,我們使用 Vuex 來管理 todo 列表的狀態(tài),包括添加新 todo、切換 todo 狀態(tài)、刪除 todo 等功能。在模板中,我們使用了 v-for 指令來渲染 todo 列表,并通過 Vuex 的 getters 計(jì)算屬性顯示已完成和未完成的 todo 列表。

小結(jié)

使用vuex能夠?qū)崿F(xiàn)組件之間的通信,它是一個(gè)狀態(tài)管理機(jī)制,集中管理組件共享狀態(tài)。

責(zé)任編輯:武曉燕 來源: 海燕技術(shù)棧
相關(guān)推薦

2025-03-07 00:00:10

2021-08-03 08:35:36

Vuex數(shù)據(jù)熱更新

2025-03-07 00:36:01

VuePiniaVuex

2021-07-16 22:49:50

PiniaVuex替代品

2021-11-15 08:16:05

Vue 技巧 開發(fā)工具

2021-07-26 23:57:48

Vuex模塊項(xiàng)目

2019-08-09 10:33:36

開發(fā)技能代碼

2022-03-27 09:06:25

vuexActionsMutations

2024-12-20 09:12:00

Vue項(xiàng)目Pinia

2022-02-08 11:45:03

PiniaVuex前端

2020-07-29 19:40:36

Vue 3.0Vue前端

2022-06-29 10:04:01

PiniaVuex

2025-03-27 12:18:13

vuex存儲(chǔ)持久化

2021-05-20 07:26:21

工具Vuex Vue.js

2022-02-09 23:02:53

Vuex開發(fā)管理模式

2021-06-01 20:38:04

Vuex對(duì)象import

2021-10-20 08:49:30

Vuexvue.js狀態(tài)管理模式

2024-06-07 09:30:22

vue2Vuex存儲(chǔ)

2024-01-15 06:51:18

字典前端開發(fā)

2021-06-01 07:55:43

Vuex使用流程
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)