vuex用来管理vue的所有组件状态。 首先下载vuex,”vuex”:”^3.0.1”,运用”vuex-persistedstate”来对数据进行缓存。下载”vuex-persistedstate” 在文件中引入:(新建一个store文件夹,在文件夹下的index.js文件进行如下编写)
<pre class="prettyprint"><code class=" hljs python"><span class="hljs-keyword">import Vue <span class="hljs-keyword">from <span class="hljs-string">'vue'
<span class="hljs-keyword">import Vuex <span class="hljs-keyword">from <span class="hljs-string">'vuex'
<span class="hljs-keyword">import createPersistedState <span class="hljs-keyword">from <span class="hljs-string">'vuex-persistedstate'
Vue.use(Vuex)
定义简单模块:
<pre class="prettyprint"><code class=" hljs perl">const module = {
<span class="hljs-keyword">state: {
user: {
name: <span class="hljs-string">'rookie'
}
},getters: {},mutations: {
setUser(<span class="hljs-keyword">state,payload){
<span class="hljs-keyword">if(payload.hasOwnProperty(<span class="hljs-string">'name')){
<span class="hljs-keyword">state.user.name = payload.name
}
}
},plugins: [createPersistedState()]
}
上面是一个简单的vuex,在vuex中对应的store应用,在store中包含组件的共享状态state和改变状态的方法(暂且称作方法)mutations。注意state相当于对外的只读状态,不能通过store.state.user.name来更改,使用store.commit方法通过触发mutations改变state。 在页面中获取记录的值name为rookie:
<pre class="prettyprint"><code class=" hljs avrasm">mounted(){
console<span class="hljs-preprocessor">.log(this.$store<span class="hljs-preprocessor">.state<span class="hljs-preprocessor">.user<span class="hljs-preprocessor">.name)<span class="hljs-comment">;
}
store.state为获取store中的值,此时在my页面中打印出来的值为rookie,而我们想要修改name的值,则需要借助store.commit方法来触发mutations:
<pre class="prettyprint"><code class=" hljs bash">this.<span class="hljs-variable">$store.commit(<span class="hljs-string">'setUser',{name: <span class="hljs-string">'kuke_kuke'})
在mutations中找到setUser,第二个参数payload为传入的对象{name: ‘kuke_kuke’},调用方法hadOwnProperty来判断传入的对象是否有name属性,从而修改state中的值,此时在页面中再次打印user.name的值为’kuke _ kuke’。 最后导出模块:
<pre class="prettyprint"><code class=" hljs d"><span class="hljs-keyword">const store = <span class="hljs-keyword">new Vuex.Store(<span class="hljs-keyword">module)
<span class="hljs-keyword">export <span class="hljs-keyword">default store
别忘记在main.js中获取模块并使用:
<pre class="prettyprint"><code class=" hljs cs">import store <span class="hljs-keyword">from <span class="hljs-string">'./store'
<span class="hljs-keyword">new Vue({
store
})
作者:rookie.he(kuke_kuke) 博客链接: 欢迎关注支持,谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。