标签:store ash 之间 改变 网页 设置 tms npm methods
0,本来想只用vue就可以做项目了,后来发现不行;一个网页被切分成若干个组件,组件之间是需要数据传递的,因此引入了vuex这个集中式存储、管理的状态管理模式。
1,安装vuex:
npm install --save vuex
在main.js中引入:
import Vuex from ‘vuex‘ Vue.use(Vuex)
2,创建数据源文件vuex/store.js
import Vue from ‘vue‘
import Vuex from ‘vuex‘
Vue.use(Vuex)
const store = new Vuex.Store({
// 定义状态
state: {
msg: ‘我是Hello模块‘
},
// 改变状态
mutations: {
setMsg(state,msg){
state.msg = msg
}
}
})
export default store
并在main.js 中引入
import store from ‘./vuex/store‘ Vue.prototype.$store = store
3,重写hello.vue,使用vuex管理的状态变量
<template>
<div class="hello">
<h2>{{ msg }}</h2>
<ul>
<li><a href="#/game">我是一个链接</a></li>
</ul>
</div>
</template>
<script>
export default {
name: ‘hello‘,
data () {
return {
msg: this.$store.state.msg //我是Hello模块
}
}
}
</script>
4,在 game.vue 中改变这个状态变量的值
<template>
<div class="game">
<h2>{{ msg }}</h2>
<ul>
<li><a href="#/">返回</a></li>
</ul>
</div>
</template>
<script>
export default {
name: ‘game‘,
data () {
return {
msg: ‘我是Game模块‘
}
},
mounted:function(){
this.sendMsg()
},
methods:{
sendMsg:function(e){
this.$store.commit(‘setMsg‘,this.msg);//改变状态
}
}
}
</script>
hello.vue中的msg被重新设置。
解决了组件之间的通信问题,就可以大胆地合理规划组件拉。^_^
标签:store ash 之间 改变 网页 设置 tms npm methods
原文地址:http://www.cnblogs.com/phptree/p/7282153.html