Vuex의 돌연변이를 이해하는 방법은 무엇입니까? 그것을 사용하는 방법?

青灯夜游
풀어 주다: 2021-02-11 08:57:37
앞으로
3362명이 탐색했습니다.

Vuex의 돌연변이를 이해하는 방법은 무엇입니까? 그것을 사용하는 방법?

관련 권장 사항: "vue.js Tutorial"

데이터 변경 방법 모음이 포함된 돌연변이에 대한 일반적인 이해는 Vuex 설계에서 매우 중요한 점, 즉 모든 논리적 방법입니다. 처리 데이터는 mutation 내부에 배치되며, 데이터와 뷰가 분리됩니다.

돌연변이를 사용하는 방법은 무엇인가요?

Mutation 구조: 각 mutation마다 문자열 형식의 이벤트 유형(type)과 콜백 함수(handler)가 있는데, 이는 구독 게시와 다소 유사한 {type:handler()}로도 이해될 수 있습니다. 먼저 이벤트를 등록하고, 응답 유형이 트리거되면 handker()를 호출합니다. 유형 호출 시에는 store.commit 메소드를 사용해야 합니다.

 const store = new Vuex.Store({
    state: {
        count: 1
        },
    mutations: {
   		 increment (state) {      //注册事件,type:increment,handler第一个参数是state;
  		  // 变更状态
   		state.count++}}})
   store.commit('increment')   //调用type,触发handler(state)
로그인 후 복사

Payload: 간단히 이해하면 매개변수 핸들러(스테이지, 페이로드)를 핸들러(스테이지)에 전달하는 것이 일반적입니다.

  mutations: {
 increment (state, n) {
     state.count += n}}
 store.commit('increment', 10)
로그인 후 복사

mutation-types: 공동 개발을 촉진하기 위해 상수를 별도의 파일에 넣습니다.

mutation-types.js

export const SOME_MUTATION = 'SOME_MUTATION'
로그인 후 복사

store.js

import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
  const store = new Vuex.Store({
    state: { ... },
    mutations: {
     // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
    // mutate state
  }
}
})
로그인 후 복사

commit: 구성 요소에서 커밋을 사용하여 변형을 제출하거나 mapMutations 도우미 함수를 사용하여 구성 요소의 메서드를 store.commit 호출에 매핑할 수 있습니다. 루트 노드 저장소에 주입됨) this.$store.commit('xxx')

import { mapMutations } from 'vuex'
export default {
methods: {
  ...mapMutations([
    'increment' // 映射 this.increment() 为 this.$store.commit('increment')]),
  ...mapMutations({
    add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
  })}}
로그인 후 복사

소스 코드 분석

function registerMutation (store, type, handler, path = []) {
 //4个参数,store是Store实例,type为mutation的type,handler,path为当前模块路径
    const entry = store._mutations[type] || (store._mutations[type] = 
[])  //通过type拿到对应的mutation对象数组
     entry.push(function wrappedMutationHandler (payload) {
     //将mutation包装成函数push到数组中,同时添加载荷payload参数    
     handler(getNestedState(store.state, path), payload)
     //通过getNestedState()得到当前的state,同时添加载荷payload参数
   })
 }
로그인 후 복사

커밋: 돌연변이 호출

commit (type, payload, options) {
  // 3个参数,type是mutation类型,payload载荷,options配置
    if (isObject(type) && type.type) {
       // 当type为object类型,
      options = payload
      payload = type
      type = type.type
  }
 const mutation = { type, payload }
 const entry = this._mutations[type]
   // 通过type查找对应的mutation
 if (!entry) {
  //找不到报错
   console.error(`[vuex] unknown mutation type: ${type}`)
   return
 }
 this._withCommit(() => {
   entry.forEach(function commitIterator (handler) {
   // 遍历type对应的mutation对象数组,执行handle(payload)方法
   //也就是开始执行wrappedMutationHandler(handler)
     handler(payload)
   })
 })
 if (!options || !options.silent) {
   this._subscribers.forEach(sub => sub(mutation, this.state))
    //把mutation和根state作为参数传入
 }
}
로그인 후 복사

구독자: 스토어의 돌연변이 구독

subscribe (fn) {
const subs = this._subscribers
if (subs.indexOf(fn) < 0) {
  subs.push(fn)
  }
return () => {
  const i = subs.indexOf(fn)
  if (i > -1) {
    subs.splice(i, 1)
    }
  }
 }
로그인 후 복사
더 많은 프로그래밍 관련 지식을 보려면

프로그래밍 교육을 방문하세요! !

위 내용은 Vuex의 돌연변이를 이해하는 방법은 무엇입니까? 그것을 사용하는 방법?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:csdn.net
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!