이 글은 Vue.js 상태 관리 모드 Vuex(코드 예제)의 설치 및 사용에 대한 것입니다. 필요한 친구들이 참고할 수 있기를 바랍니다. 당신.
먼저 vue.js 2.0 개발 환경에 vuex를 설치합니다:
npm install vuex --save
그런 다음 main.js에 추가합니다: #🎜🎜 #
import vuex from 'vuex' Vue.use(vuex); const store = new vuex.Store({//store对象 state:{ show:false, count:0 } })
new Vue({ el: '#app', router, store,//使用store template: '<app></app>', components: { App } })
store.commit('increment') console.log(store.state.count) // -> 1
State
// 创建一个 Counter 组件 const Counter = { template: `<p>{{ count }}</p>`, computed: { count () { return this.$store.state.count } } }
mapState 보조 함수
// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) }
매핑된 계산된 속성의 이름이 상태의 하위 노드 이름과 동일한 경우 , mapState 문자열 배열에 문자를 전달할 수도 있습니다.
computed: mapState([ // 映射 this.count 为 store.state.count 'count' ])
Getter
Getter는 상태를 첫 번째 매개변수로 받아들입니다.
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) } } })
Accessed via Properties
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 다른 getter를 두 번째 매개변수로 사용할 수도 있습니다:
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } } store.getters.doneTodosCount // -> 1
구성 요소에 사용: #🎜🎜 #
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变更状态 state.count++ } } })
store.commit('increment')
// ... mutations: { increment (state, n) { state.count += n } }
store.commit('increment', 10)
// ... mutations: { increment (state, payload) { state.count += payload.amount } }
store.commit('increment', { amount: 10 })
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
store.dispatch('increment')
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 })
관련 권장사항:
Vue.js of vuex(상태 관리)# 🎜🎜#위 내용은 Vue.js 상태 관리 모드 Vuex 설치 및 사용(코드 예시)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!