Vue Vuex state mutations
Posted chenyishi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue Vuex state mutations相关的知识,希望对你有一定的参考价值。
Vuex
解决不同组件的数据共享,与数据持久化
1.npm install vuex --save
2.新建store.js 并引入vue vuex ,Vue.use(Vuex)
3.state在vuex中用于存储数据
var state = {
count:1
}
4.mutations里放的是方法,主要用于改变state中的数据
var mutations = {
incCount(){
++state.count;
}
}
5.实例化vuex.Store
consta store = new Vuex.Store({
state,
mutations
})
6.export default store;
7.组件A中引入store
import store from ‘../store.js‘
8.注册
mounted(){},
store
9.
通过this.$store.state.count引用属性
通过this.$store.commit.(‘incCount‘))引用方法
import Vue from ‘vue‘; import Vuex from ‘vuex‘; Vue.use(Vuex); var state = { count:1 } const mutations = { run(){ ++state.count; } } const store = new Vuex.Store({ state, mutations }); export default store;
<template> <div id="app"> <router-link to="/home">Home组件</router-link> <router-link to="/news">News组件</router-link> <hr> <router-view></router-view> </div> </template> <script> export default { name: ‘app‘, data () { return { msg: ‘Welcome to Your Vue.js App‘ } } } </script> <style lang="scss"> </style>
<template> <div id="news"> News组件 {{this.$store.state.count}} </div> </template> <script> import store from ‘../utils/store.js‘ export default { data() { return{} }, store }; </script>
<template> <div id="home"> Home组件 {{this.$store.state.count}} <br> <button @click="addstate()">添加state</button> </div> </template> <script> import store from ‘../utils/store.js‘ export default { data() { return{} }, store, methods:{ addstate(){ this.$store.commit(‘run‘) } } }; </script>
以上是关于Vue Vuex state mutations的主要内容,如果未能解决你的问题,请参考以下文章