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'))引用方法
10.getters类似于计算属性,改变state里面的count数据的时候,触发getters里的方法,获取新的值
var getters = {
computedCount : (state)=>{
return state.count*2
}
}
通过 this.$store.getters.computedCount调用
11.Action类似于mutation,不同在于Action提交的是mutation,而不是直接改变状态。Action可包含任意异步操作
var actions = {
incMutationsCount(context){
context.commit('incCount') /*执行mutations里的incCount方法*/
}
}
通过this.$store.dispatch('incMutationsCount')调用
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>