Click the blue “dada front end” to follow me!
Add a “star sign”, an article every day, learn programming together
Login registration, talk about login, need a user name, user name prompt content for please enter the user name, password prompt for 8-18 digits, does not contain special characters number, letter combination. There is also a click button.
<view class="input-content">
<view class="input-item">
< text class = "user name" > user name < / text >
<input v-model=" query.username "Placeholder =" please enter a user name "/ >
</view>
<view class="input-item">
< text class = "password" > password < / text >
<input v-model="query.password"
Placeholder = "8-18 digit combination of numbers and letters without special characters"
maxlength="20"
password />
</view>
</view
< button class = "confirm BTN" @ Click = "tologin" > login < / button >
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="app">
{{count}}
<button @click='increment'>+</button>
</div>
<script></script>
</body>
</html>
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
}
});
import { mapState } from 'vuex';
new Vue({
el: '#app',
store,
data: {
},
computed: mapState([
'count'
]),
});
Vuex is designed for vue.js State management mode of application development, which uses centralized storage to manage the state of all components of the application, and changes in a predictable way with the corresponding rule state.
What is state management mode?
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
State is the data source to drive the application, view is to map state to view in a declarative way, and actions is to respond to state changes caused by user input on view.
When our application encounters multiple components sharing state, the simplicity of one-way data flow is easy to be destroyed.
First, multiple views depend on the same state.
Second, behaviors from different views need to change the same state.
In the first case, the method of parameter transfer will be very cumbersome for multi-layer nested components, and it can’t do anything for the state transfer between sibling components.
In the second case, we will use parent-child component direct reference or events to change and synchronize multiple copies of the state.
The shared state of components can be extracted and managed in a global singleton mode. In this way, the component tree constitutes a huge “view”, no matter where in the tree, any component can get state or trigger behavior.
By defining and isolating various concepts in state management, the independence between view and state is maintained through mandatory rules.
Vuex is designed for vue.js The state management library is designed to make use of vue.js In order to update the state efficiently, a fine-grained data response mechanism is proposed.
The core of every vuex application is the store warehouse, which is a container containing most of the States.
The state storage of vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly.
The only way to change the state of a store is to explicitly submit commit mutation, which can easily track the change of each state.
Understanding of store
After installing vuex, let’s create a store.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
Can pass store.state To get the state object, and then store.commit Method triggers a state change.
store.commit('increment');
console.log(store.state.count);
By submitting a mutation instead of directly changing it store.state.count 。
Core concepts: state, getter, mutation, action, module.
Single state
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="app">
{{ count }}
</div>
<script></script>
</body>
</html>
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
}
});
new Vue({
el: '#app',
store,
computed: {
count () {
return this.$store.state.count
}
}
});
A single state tree contains all the application level states with one object.
//Create a counter component
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
const app = new Vue({
el: '#app',
//Provide the store object to the "store" option, which can inject the instance of the store into all the subcomponents
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
By registering the store in the root instance, the store instance will be injected into all the subcomponents under the root component, and the subcomponents can be accessed through this. $store.
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
Mapstate helper function
//In the separately built version, the auxiliary function is Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
//Arrow functions make the code more concise
count: state => state.count,
//The string parameter 'count' is equivalent to ` state = > state.count `
countAlias: 'count',
//In order to be able to use 'this' to get local state, you must use regular functions
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
When the name of the mapped calculated property is the same as the name of the child node of the state.
computed: mapState([
//Mapping this.count For store.state.count
'count'
])
Object expansion operator
The mapstate function returns an object.
computed: {
localComputed () { /* ... */ },
//Use the object expansion operator to blend this object into an external object
...mapState({
// ...
})
}
Getter
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
The return value of getter will be cached according to its dependency, and will be recalculated only when its dependency value changes.
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
Access through properties
Getter will be exposed store.getters Object.
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
Access by method
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2)
Mapgetters helper function
The mapgetters auxiliary function only maps the getters in the store to the local calculation properties.
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
//Using object expansion operators to mix getters into computed objects
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
mapGetters({
//Put` this.doneCount `Map to ` this$ store.getters.doneTodosCount `
doneCount: 'doneTodosCount'
})
Vuex. Vue has its own store mode. In fact, it registers an object globally to realize data sharing. It is suitable for small projects with less data.
The five cores of vuex are state, getters, mutations, actions and module.
The four auxiliary functions of vuex are mapstate, mapgetters, mapmutations and mapactions.
The workflow of vuex
Client operation event, dispatch calls an action.
The corresponding action processing parameters, such as interface, logical operation, value transfer, type of commit, mutation, introduce the function of type trigger object, modify the state, after the state is updated, the view view will be re rendered under the effect of render.
Mapstate and mpagetter can only be used in the computed calculated property.
The amount of time that mapMutations and mapActions can be used can only be invoked in methods.
<script>
import { mapState , mapMutations , mapActions , mapGetters } from 'vuex';
export default {
data(){
return{
}
},
computed:{
...mapState({
counts:(state) => state.count
}),
//Mapstate equals this
// counts(){
// return this.$store.state.count
// },
...mapGetters({
getternum:'doneTodos'
}),
//Mapgetters equals this one
// getternum(){
// return this.$store.getters.doneTodos
// }
},
methods:{
...mapMutations({
addnum:'addNum'
}),
//Mapmutations equals this one
// addnum1(){
// this.$store.commit('addNum')
// },
...mapActions({
actionnum:'actionNumAdd'
}),
//Mapactions equals this
// actionnum6(){
// this.$store.dispatch('actionNumAdd')
// }
}
}
</script>
call
method
auxiliary function
state
this.$store.state. xxx
mapState
getters
this.$store.getters. xxx
mapGetters
mutations
this.$store.cmmit((xxx)
mapMutations
actions
this.$store.dispatch(xxx )
mapActions
states.js
const state = {
count:0
}
export default state
getter.js
const getters = {
docount:(state,getters) => {
return state.counts
}
}
export default getters
Mutation
The only way to change the state in vuex’s store is to submit a mutation. Each mutation has a string event type and a callback function.
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
//Change status
state.count++
}
}
})
store.commit('increment')
Submit load
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
The load is mostly an object
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
Object style submission
store.commit({
type: 'increment',
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
Object expansion operator
state.obj = { ...state.obj, newProp: 123 }
Submit the mutation in the component
this.$store.commit('xxx')
Using the mapmutations helper function
Map the methods in the component to store.commit call
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // will` this.increment () 'mapped to' this$ store.commit ('increment')`
//'mapmutations' also supports loads:
'incrementby' // will` this.incrementBy (amount) ` is mapped to ` this$ store.commit ('incrementBy', amount)`
]),
...mapMutations({
Add: 'increment' // add` this.add () 'mapped to' this$ store.commit ('increment')`
})
}
}
In vuex, mutations are synchronous transactions
store.commit('increment')
//Any state changes caused by "increment" should be completed at this point.
Action, the action submits the mutation, not directly changes the state. An action can contain any asynchronous operation.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
actions: {
increment ({ commit }) {
commit('increment')
}
}
Distribute action
Action passed store.dispatch Distribution trigger:
store.dispatch('increment')
Asynchronous operations can be performed inside an action.
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions supports load mode and object mode
//Distributed as load
store.dispatch('incrementAsync', {
amount: 10
})
//Distribute as objects
store.dispatch({
type: 'incrementAsync',
amount: 10
})
Distribute actions in components
this.$ store.dispatch ('xxx ') distribution action
Use the mapactions helper function to map the methods of a component to store.dispatch call
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment' // will` this.increment () 'mapped to' this$ store.dispatch ('increment')`
//Mapactions also supports payload:
'incrementby' // will` this.incrementBy (amount) ` is mapped to ` this$ store.dispatch ('incrementBy', amount)`
]),
...mapActions({
Add: 'increment' // add` this.add () 'mapped to' this$ store.dispatch ('increment')`
})
}
}
module
Vuex divides the store into modules, and each module has its own state, mutation, action and getter.
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state . A // - > module a status
store.state . B // - > module B status
login.vue
<view class="input-content">
<view class="input-item">
< text class = "tit" > user name < / text >
<input v-model=" query.username "Placeholder =" please enter a user name "/ >
</view>
<view class="input-item">
< text class = "tit" > password < / text >
<input v-model=" query.password "Placeholder =" 8-18 digit combination of numbers and letters without special characters "MaxLength =" 20“
password @confirm="toLogin" />
</view>
</view>
< button class = "confirm BTN" @ Click = "tologin": Disabled = "logging" > login < / button >
import {
mapMutations
}
from 'vuex';
Mobile: ', // phone number
Password: ', // password
logining: false ,
...mapMutations(['login']),
toLogin() {
this.logining = true;
loginApi(this.query).then(res => {
if(res.data.code === 1) {
this.$api.msg(res.data.msg)
...
}).catch(res => {
this.logining = false;
})
}
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
State: {// where the global variable is defined
Haslogin: false, // do you want to log in
Userinfo: {}, // used to store user account data
},
Mutations: {// at the global method definition
login(state, provider) {
},
logout(state) {
},
},
actions: {
}
})
export default store
☆ END ☆
Reference document source: official document of vuex https://vuex.vuejs.org/zh/
Add group front end communication group
Scan code, add group – technology field – City – name
At present, the content of the article involves front-end knowledge points, including Vue, JavaScript, data structure and algorithm, actual combat drill, node full stack front-line technology, closely following the pace of development of the industry, presenting web front-end field, network principle and other easy to understand to small partners. For more information, please visit dada front-end website: www.dadaqianduan.cn
PUSHRecommendationReadread
1、How much do you know about this, new, bind, call, apply? I’ll tell you
2、Why learn JavaScript Design Patterns, because it’s the core
3、An article takes you to closures and advanced functions in JavaScript
4、Knowledge points of interview questions in HR interview ES6
Think this article is helpful to you? Please share with more people
Focus on “dada front end” and add star logo to improve front end skills
This is a official account with a quality and attitude.