bilibili学习之vuex 中的mutations

 Vuex的官网链接https://vuex.vuejs.org/zh/

vuex也是插件,需要安装

npm install vuex --save

// 1.提取出一个公共的store对象,用于保存在多个组件中共享的状态
//2.将store对象放置在new Vue对象中,这样可以保证在所有的组件中都可以使用到
//3.在其他组件中使用store对象中保存的状态即可
//通过this.$store.state.属性的方式来访问状态
//通过this.$store.commit('mutation中方法')来修改状态 

创建store目录,下面建一个index.js。

  • 安装插件
  • 创建对象
  • 导出

state、mutations、actions 、getters 、modules都是方法

然后在main.js中导入:

在APP.vue中写:

<template>
	<div id="app">
		<h2>{{ message }}</h2>
		<h2>{{ $store.state.counter  }}</h2>
		<button @click="addition">+</button>
		<button @click="subtraction">-</button>
		<h2>HELLO VUE内容</h2>
		<hello-vuex ></hello-vuex>
	</div>
</template>

<script>
	import HelloVuex from './components/HelloVuex.vue'
	export default {
		name: 'app',
		components:{
			HelloVuex
		},
		data(){
			return{
				message:'我是APP的内容',
			
			}
		},
		methods:{
			addition(){
				this.$store.commit('increment')
			},
			subtraction(){
				this.$store.commit('decrement')
			}
		}
	}
</script>

<style>

</style>

 在components目录下建HelloVuex.js

<template>
	<div>
		<h2>{{ $store.state.counter }}</h2>
	</div>
</template>

<script>
	export default {
		name:"HelloVuex",
		
	}
	
</script>

<style>
</style>

在index.js中:

import Vue from 'vue'
import Vuex from 'vuex'
//1安装插件
Vue.use(Vuex)

//2创建对象
const store = new Vuex.Store({
	state:{
		counter:100
	},
	mutations:{
		increment(state){
			state.counter++
		},
		decrement(state){
			state.counter--
		}
	},
	actions:{
		
	},
	getters:{
		
	},
	modules:{
		
	}
})
export default store

效果图

 

 如果要修改state中的内容,要通过mutations进行修改,安装插件Devtools可对修改的内容进行监听,当有异步操作时要使用actions。具体可到官方网站查看。

我还没学会那。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值