Vux的说明
概念:專門在Vue中實現(xiàn)集中式狀態(tài)(數(shù)據(jù))管理的一個Vue插件,對vue應(yīng)用中多個數(shù)組的共享狀態(tài)進(jìn)行集中式管理(讀/寫),這也是一種組件間通信的方式,且適用于任意組件間通信。
使用場景:
vuex項目建立步驟
注意:
使用vue2的腳手架,則安裝vuex3
使用vue3的腳手架,則安裝vuex4
新建文件夾store,與components同一級
在store文件夾下新建index.js文件
index.js文件
import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex)const actions={} //用于響應(yīng)組件中的動作 const mutations={} //用于操作數(shù)據(jù) const state={} //用于存儲數(shù)據(jù)//創(chuàng)建并暴露store export default new Vuex.Store({actions,mutations,state })步驟順序:1,3,24
具體使用:
P.vue文件
store index.js文件
...... const actions={jia(context,value){context.commit('JIA',value)} }const mutations={JIA(state,value){state.sum+=value} }const state={ sum=0 } ......組件中讀取vuex中的數(shù)據(jù):$store.state.sum
組件中修改vuex中的數(shù)據(jù):$store.dispatch('actions中的方法名',數(shù)據(jù))或$store.commit('mutations中的方法名',數(shù)據(jù))
若沒有網(wǎng)絡(luò)請求或其他業(yè)務(wù)邏輯,組件中也可以越過actions,即不寫diapatch,直接編寫commit
具體例子
項目結(jié)構(gòu)
index.js文件
App.vue文件
<template><div><Person></Person></div> </template><script> import Person from './components/Person.vue' export default ({name:'App',components:{Person}}) </script>main.js文件(引入store)
import Vue from 'vue' import App from './App.vue' import store from './store/index'Vue.config.productionTip = falsenew Vue({render: h => h(App),store }).$mount('#app')Person.vue文件
<template><div><input type="text" placeholder="請輸入要添加的姓名" v-model="name"><button @click="add()">添加</button><ul><li v-for="p in personList" :key="p.id">{{p.name}}</li></ul></div> </template><script>// import {mapMutations,mapState} from 'vuex'import {nanoid} from 'nanoid'export default{name:'School',data(){return{name:'',// person:{// id:nanoid(),// pname:'' // }}},methods:{add(){const person = {id:nanoid(),name:this.name}this.$store.commit("Add",person)this.name=""}// ...mapMutations({add:'Add'}),},computed:{personList(){return this.$store.state.personlist} // ...mapState({personList:'personlist'})}} </script>效果圖
總結(jié)
- 上一篇: 怎样用计算机中的画笔,Word2010中
- 下一篇: 记一次服务器被攻击后的经历