安装Vuex:
npm install Vuex -S
在main.js中引入
import Vue from 'vue' import App from './App' import Vuex from 'vuex' import store from './vuex/store' Vue.use(Vuex) /* eslint-disable no-new */ new Vue({ el: '#app', store, render: h => h(App) })
创建store.js
在 src 目录下创建 vuex ,在文件夹vuex中创建store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state:{ author : 'hello' } }) export default store
映射到组件:
<template> <footer class="footer"> <p> Copyright © {{author}} - 2016 All rights reserved </p> </footer> </template>
<script> export default{ name: '....', comptude:{ author(){ return this.$store.state.author } } } </script>
在其他组件中修改状态:
<template> <div> <input type='text' v-model='text' @change='getAuthor'> </div> </template> <script> export default { data(){ return{ text:'' } }, methods:getAuthor:function(){ this.$store.state.author = this.text } } </script>
这样就实现了input状态发生改变时,author的值也跟着发生改变,达到了跨组件修改值的方法。
官方写法
store.js:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.store({ state:{ author : 'hello' }, mutations:{ newAuthor(state,msg){ state.author = msg } } }) export default store
然后在组件内修改setAuthor方法:
methods:{ setAuthor:function(){ this.$store.commit('newAuthor',this.text) } }