vue之vuex的简单使用

无敌的宇宙
无敌的宇宙
擅长邻域:Java,HTML,JavaScript,MySQL,支付,退款,图片上传

分类: vue 标签: vuex的简单使用 vue实现数据共享

2021-11-27 23:24:05 1150浏览

最新在学习vue,简单的记录一下 先了解vuex有啥用? vuex就是管理各组件的共有数据共享数据,向我们以前学习的data是组件的私有数据,需要通过props或者消息订阅离开完成各组件之间的传参,如果组件很多那么程序会写的很复杂,不好维护,2️⃣vuex则很好地解决了这个问题 安装vuex

最新在学习vue,简单的记录一下

先了解vuex有啥用?

vuex就是管理各组件的共有数据共享数据,向我们以前学习的data是组件的私有数据,需要通过props或者消息订阅离开完成各组件之间的传参,如果组件很多那么程序会写的很复杂,不好维护,2️⃣vuex则很好地解决了这个问题

安装vuex

npm install --save vuex

创建store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//状态对象
const state={
counter:0
}
//包含多个更新state函数的对象
const mutations={
ADD(state){
state.counter++
},JJ(state){
state.counter--
}
}
//包含多个事件回调函数的对象,actions调用mutations
const actions={
add({commit}){
commit('ADD');
},
jj({commit}){
commit('JJ');
},
//待条件的action
jjadd({commit,state}){
if(state.counter%2===1)
commit('ADD');
},
autoadd({commit}){
setTimeout(()=>{
commit('ADD');
},1000)
}
}
//包含多个更新state函数的对象
const getters={
desc(state){//不需要亲自调用,只需要读取属性值
return state.counter%2===0?'偶数':'奇数';
}
}
export default new Vuex.Store({
state,//状态对象
mutations,//包含多个更新state函数的对象
actions,//包含多个事件回调函数的对象
getters//包含多个getter计算属性函数的对象
})


mian.js引入store.js

//入口js,创建vue实例
import Vue from 'vue'

import App from './App.vue'

import store from './store'


new Vue({
el:'#app',
components:{
App,

},
template:'<App/>',
store,//所有的组件对象都多了一个$store属性
})


app.vue

<template>
<div>
<p>clicked {{$store.state.counter}},counter is {{desc}}</p>
<p>
<button @click="add">+</button>
<button @click="jj">-</button>
<button @click="jjadd">奇数+1</button>
<button @click="autoadd">过一秒自动+1</button>
</p>
</div>

</template>

<script>

export default {

name:'App',
data(){
return {

}
},
computed:{
desc(){
return this.$store.getters.desc;
}
},
methods:{
add(){

this.$store.dispatch('add');//触发store中的actions调用
},
jj(){

this.$store.dispatch('jj');//触发store中的actions调用
},
jjadd(){
this.$store.dispatch('jjadd');//触发store中的actions调用
},
autoadd(){
this.$store.dispatch('autoadd');//触发store中的actions调用
}
}

}
</script>
<style>


</style>


好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695