加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vuex store的运用

发布时间:2020-12-16 23:28:45 所属栏目:百科 来源:网络整理
导读:vuex用来管理vue的所有组件状态。 首先下载vuex,”vuex”:”^3.0.1”,运用”vuex-persistedstate”来对数据进行缓存。下载”vuex-persistedstate” 在文件中引入:(新建一个store文件夹,在文件夹下的index.js文件进行如下编写) pre class="prettyprint"

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) 博客链接: 欢迎关注支持,谢谢!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读