series
- [juejin. Cn/post / 684490…]. Vue-admin detailed annotation, must do the project series (a)
- [juejin.cn/post/684490… detailed notes, must do the project series (2)
- [juejin. Cn/post / 684490…]. Vue-admin detailed comments, must do the project series (3) to the server to resolve the error
- The sparrow is small and complete: [project address github.com/whylisa/vue…]
- Project address: [github.com/whylisa/vue…]
Vuex
What is it (the website is pretty good)
Vuex
Vue is a state management tool in Vue- State, i.e., data
- The state management tool is used to manage data in components of a Vue project
Why Vuex
Vuex
Should only be used in medium to large complex Vue projects- Vuex is not required for small projects
The specification of Vuex
- Vuex manages all data that needs to be shared within a project in a centralized manner. As long as the same data is shared between components, it can be achieved through Vuex
- predictability
- Vuex is simply an enhanced version of bus
State management
- The first state management idea of the front end was introduced by Flux in React
- Flux not only puts forward the idea of front-end state management, but also provides the corresponding implementation
- Other state management libraries:
Flux
/Redux
/Mobx
/Vuex
The difference between Actions and mutations
- Why is the asynchronous operation encapsulated in Action and the synchronous operation on mutations in VUEX? – Yuxi’s answer – Zhihu
- Principle: Synchronous operation in
mutations
Asynchronous operations should be placed inactions
中 - Reason: In order to track state changes with DevTools, asynchronous actions can only be tracked by DevTools if they are placed in actions
- Actions such as setTiemout/axios.get() should be done in actions
The core concepts in Vuex
- store
The characteristics of Vuex
Vuex
The data in is also reactive (bidirectional binding)
Case structures,
- Technical point
- vuex
- Vue cli – 2.0
- Todos template
- Project directory
- Now create a store folder in SRC, create a new index.js file, and initialize the store as follows
import Vue from 'vue'/ / into the vue
import Vuex from 'vuex'/ / introduce vuex
/ / installation
Vue.use(Vuex)
// Initialize state
const state = {}
// mutations
const mutations = {}
Vuex.store = vuex.store = vuex.store
const store = new Vuex.Store({
state,
mutations
})
export default store / / export store
Copy the code
- We then import it in main.js and mount it to an instance of vue
// 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 styles
import '@/assets/index.css'
/ / import store
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app'.// Associate Vuex (Store) and Vue instances together
store,
components: { App },
template: '<App/>'
})
Copy the code
- Then configure app. vue, import the Todos template component into app. vue, and our store is configured
Function complete
- Renderings (PS: Classic to Vomit)
- Now we perfect the store, fill in the data, and carry out the unified operation of some states of adding, deleting and updating.
import Vue from 'vue'/ / into the vue
import Vuex from 'vuex'/ / introduce vuex
/ / installation
Vue.use(Vuex)
// Initialize state
const state = {
todos: [{id: 1.name: 'the bald'.done: false },
{ id: 2.name: 'Girlfriend ran away'.done: false },
{ id: 3.name: 'More power in the left hand'.done: true}}]/ / mutations configuration
const mutations = {
// The task status is changed according to the id
changeDone(state, payload) {
// 1 Find the current task by id
const curTodo = state.todos.find(item= > item.id === payload.id) // the arrow function
// the state of 2 is reversedcurTodo.done = ! curTodo.done },// Add task methods
addTodo(state, payload) {
const length = state.todos.length
const id = length === 0 ? 1 : state.todos[length - 1].id + 1
state.todos.push({
id,
name: payload.name,
done: false})},// Delete the task method
delTodo(state, payload) {
state.todos.splice(payload.index, 1)},// Update the task method
updateTodo(state, payload) {
// Find the current task to update
const curTodo = state.todos.find(item= > item.id === payload.id)
// Change the name
curTodo.name = payload.name
},
// Clear completed tasks
clearAllDone(state) {
state.todos = state.todos.filter(item= >! item.done) } }// Actions asynchronous operations (interview site)
// Internal or submitted mutations
const actions = {
// Add tasks asynchronously
addTodoAsync(context, payload) {
SetTimeout is an asynchronous operation, but mutations are also submitted
setTimeout((a)= > {
context.commit('addTodo', {
name: payload.name
})
}, 2000)}}// getters
// Equivalent to calculated properties in Vue components, used in exactly the same way
// When you need to get some new data from the existing state (e.g., the number of unfinished tasks from the toDOS collection)
// Use getters, which evaluates attributes
const getters = {
// Number of unfinished tasks
unDoneCount(state) {
return state.todos.filter(item= >! item.done).length },// Control the display and hide of the clear completed task button
showClearDone(state) {
return state.todos.some(item= > item.done)
}
}
/ / create a store
const store = new Vuex.Store({
// Enable strict mode
// The value of NODE_ENV during development is: 'development'
// the value of NODE_ENV is: 'production'strict: process.env.NODE_ENV ! = ='production',
state,
mutations,
actions,
getters
})
export default store
Copy the code
- Then we add the TodoHeader
<template> <header class="header"> <h1>todos</h1> <input <! -- data binding --> v-model="todoName" <! --> @keyup. Enter ="addTodo" class="new-todo" placeholder="What needs to be done? <! --> autofocus> </header> </template> <script> export default {data() {return { TodoName: "}}, methods: {// Add task addTodo() {// Input input box usually we trim, Trim () === '') {return} $store.mit ('addTodo', {// name:) This.$store. Dispatch ('addTodoAsync', {name: $store. This.todoname}) this.todoname = "// When done, empty the contents of the input box}}} </script>Copy the code
- Then we manipulate the list component TodoList
<template> <section class="main"> <input id="toggle-all" class="toggle-all" type="checkbox"> <label for="toggle-all">Mark all as complete</label> <ul class="todo-list"> <! <li :class="{completed: todo.done, editing: todo.id === editId }" v-for="(todo, index) in $store.state.todos" :key="todo.id"> <div class="view"> <! - if: Because we know that the data in Vuex can only be modified through the method provided in mutations, because v-model is used in checkbox, and v-model is bidirectional binding. When the checkbox is clicked, the corresponding data will be modified. This violates the principle that data can only be modified by mutations in Vuex!! Data -> view: :checked="todo.done" First bind an event, <input class="toggle" type="checkbox" :checked="todo.done" @change="changeDone(todo.id)"> <! -- <input class="toggle" type="checkbox" v-model="todo.done"> --> <label @dblclick="showEditStatus(todo.id)">{{ todo.name }}</label> <button class="destroy" @click="delTodo(index)"></button> </div> <input class="edit" :value="todo.name" @keyup.enter="updateTodo(todo.id, Index)" ref="todoUpdate"> </li> </ul> </section> </template> <script> export default {data() {return {// temporary variable, EditId: -1}}, methods: ShowEditStatus (id) {this.editid = id}, // Update task name updateTodo(id, Const name = this.$refs.todoupDate [index]. Value this. codestore.com MIT ('updateTodo', {id,); This.editid = -1}, changeDone(id) {// call the method provided by mutations, Use this. Codestore.com MIT ('changeDone', {id})}, // Remove task delTodo(index) {this. codestore.com MIT ('delTodo', { index }) } } } </script <style> </style>Copy the code
- The bottom is a clear, direct paste code
export default {
methods: {
// Clear all completed tasks
clearAllDone() {
this.$store.commit('clearAllDone')}}}Copy the code
conclusion
- I read some blog posts, feel vueX is a myth, you guys finish my tutorial, in fact, these things.
- Big projects are really convenient, specific use: on-demand use.