Vuex结构图再仔细看
Vuex原理:
就是 把共有属性放入到一个公共的地方,进行使用
多组件共享状态, 之前操作方式,由父组件传递到各个子组件。 当路由等加入后,会变得复杂。 引入viewx 解决共享问题。
存放标准(组件是根据数据更改显示的)
state 对象数据
mutations 操作变更state数据
getters 计算state
actions 触发mutations
指挥规则标准(跟那张图有很大的关系)
App.vue 不存在数据,只有Components 声明组件儿标签名称 指挥actions
<script> import PubSub from ‘pubsub-js‘ import TodoHeader from ‘./TodoHeader.vue‘ import TodoList from ‘./TodoList.vue‘ import TodoFooter from ‘./TodoFooter.vue‘ // import storageUtils from ‘../utils/storageUtils‘ import {mapActions} from ‘vuex‘ export default { mounted(){ // 异步获取 todos数据 this.$store.dispatch(‘reqTodos‘) }, components: { TodoHeader, TodoList, TodoFooter } }; </script>
TodosList.vue
<template> <ul class="todo-main"> <TodoItem v-for="(todo,index) in todos" :todo="todo" :key="index" :index="index"></TodoItem> </ul> </template> <script> import {mapState} from ‘vuex‘ import TodoItem from ‘./TodoItem.vue‘ import storageUtil from ‘../utils/storageUtils.js‘ export default { // 声明接收标签属性 // props: [‘todos‘], // 会成为当前组件对象的属性, 可以在模板中直接访问, 也可以通过this来访问 components: { TodoItem }, computed:{ ...mapState([‘todos‘]) }, watch: { todos: { deep: true, // 深度监视 handler: storageUtil.saveTodos } } }; </script> <style> .todo-main { margin-left: 0px; border: 1px solid #ddd; border-radius: 2px; padding: 0px; } .todo-empty { height: 40px; line-height: 40px; border: 1px solid #ddd; border-radius: 2px; padding-left: 5px; margin-top: 10px; } </style>
actions 指挥调用 mutations
import {ADD_TODO, DELETE_TODO, SELECT_ALL_TODOS, CLEAR_ALL_COMPLETED,RECEIVE_TODOS} from ‘./mutation-types‘ import storageUtil from ‘../utils/storageUtils.js‘ export default { addTodo ({commit}, todo) { commit(ADD_TODO, {todo}) }, deleteTodo({commit},index){ commit(DELETE_TODO,{index}) }, selectAllTodos ({commit}, check) { commit(SELECT_ALL_TODOS, {check}) }, clearALLCompleted({commit}){ commit(CLEAR_ALL_COMPLETED) }, reqTodos({commit},todos){ setTimeout(()=>{ // 读取数据 const todos = storageUtil.readTodos() // 提交数据 commit(RECEIVE_TODOS,todos) },1000) } }
mutations 指挥调用 state 中的数据
// 引入 常量types.js 拿出来的都是变量名都是 字符串 import {ADD_TODO, DELETE_TODO, SELECT_ALL_TODOS, CLEAR_ALL_COMPLETED,RECEIVE_TODOS} from ‘./mutation-types‘ // 给名称加 []号就是成为变量的 // export default { [ADD_TODO] (state, {todo}) { state.todos.unshift(todo) }, [DELETE_TODO] (state, {index}) { state.todos.splice(index, 1) }, [SELECT_ALL_TODOS] (state,{check}){ state.todos.forEach(todo => (todo.complete = check)) }, [CLEAR_ALL_COMPLETED](state){ state.todos = state.todos.filter(todo => (!todo.complete)) }, [RECEIVE_TODOS](state,todos){ state.todos = todos } }
App最后显示 就是通过调用获取到数据
Submit 更改大小写快捷键
ctrl+ku | 改为大写 |
ctrl+kl | 改为小写 |
原文地址:https://www.cnblogs.com/reeber/p/10641722.html
时间: 2024-10-13 01:19:52