vuex
链接
安装vue包
npm install vuex
创建一个文件夹store
image
创建index.js在里面安装vuex 并初始化state对象 代码如下:
import Vue from "vue";
import Vuex from "vuex";
// 注册 vuex
Vue.use(Vuex);
//
const state = {
number:20
}
export default new Vuex.Store({
state,
})
创建mutations.js ( mutations是不能执行的异步操作)
const mutations = {
add(state,n){
state.number+=n;
}
}
export default mutations;
创建actions.js
const actions = {
add(context,n){
// setTimeout(function(){
context.commit("add",1)
// },n*1000)
}
}
export default actions;
创建getters.js (getters 实时监控 state值的变化)
const getters = {
getNewNumber(state){
return state.number+1;
}
}
export default getters;
在index.js导入它们
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/home'
import Login from '@/components/login'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
meta:{
isLogin:true
}//路由元
},{
path:'/login',
name:'login',
component:Login
}
]
})
main.js(引入状态管理store)
image
vue中映射
(1)
<template>
<div class="hello">
<h1>{{ $store.state.number }}</h1>
<h2>{{$store.getters.getNewNumber}}</h2>
<child :count="mycount"></child>
<h1>{{number}}</h1>
<button @click="add"></button>
</div>
</template>
<script>
import child from "./child.vue"
import { mapState } from "vuex"
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
mycount:1
}
},
computed:{//计算属性
...mapState({
number:state=>state.number
})
},
components:{
child
},
mounted(){
console.log(this);
},
methods:{
add(){
// $store的 commit函数就是用来调用 mutations中的函数
// this.$store.commit("add",5);
// $store的 dispatch函数就是用来调用 actions中的函数
this.$store.dispatch("add",3);
}
}
}
</script>
(2)
<template>
<div id="child">
<div>{{$store.state.number}}</div>
<div>{{count}}</div>
<button @click="more">改变count值</button>
</div>
</template>
<script>
export default {
props:['count'],
methods:{
more(){
this.count += 1;
}
}
}
</script>