真正掌握vuex的使用方法(一)
导语:vuex是什么?我的理解就是vuex是一个管理者,管理的方式是集中式管理,管理的对象即是vue.js应用程序中的众多组件的共享部分。学习的过程当中,希望按照我的步骤一步一步来进行练习!
咱们知道,vue项目当中的父子组件的交互是单通道传递,父组件通过props向子组件传递参数,而在子组件当中不不能直接修改接收的参数,而是需要通过自定义事件的方式,例如:
<!-------------------------------------父组件---------------------------------><template>
<div>
<a href="javascript:;" @click="show = true">点击</a>
<t-dialog :show.sync="show"></t-dialog>
</div></template><script><template>
<div>
{{isRed}}
<children :isRed.sync="isRed"></children>
</div></template><script>
import children from "@/components/children"
export default {
data() { return { isRed: false//向子组件传递默认值
}
}, components: {
children
}
}</script><!-------------------------------------子组件---------------------------------><template>
<div>
<input type="button" :class="{active:isRed}" value="改变" @click="change">
</div></template><script>
export default { props:['isRed'], methods:{
change(){ //取反改变父组件的值
this.$emit("update:isRed",!this.isRed);
}
}
}</script><style scoped>
.active{ background:red;
}</style>这样是不是很麻烦?如果用vuex就会变的非常简单!
1、首先用npm包管理工具,安装vuex
//因为这个包在生产环境中也要使用,所以在这里一定要加上 –savenpm install vuex --save
2、然后在main.js当中引入vuex
import vuex from 'vuex'
3、使用vuex
Vue.use(vuex);//使用vuex//创建一个常量对象const state={
isRed:false}var store = new vuex.Store({//创建vuex中的store对象
state
})4、随后在实例化Vue对象时,加入store对象:
new Vue({ el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})5、最后再将最初的示例修改为:
<!-------------------------------------父组件---------------------------------><template>
<div>
{{$store.state.isRed}} <children></children>
</div></template><script>
import children from "@/components/children"
export default { components: {
children
}
}</script><!-------------------------------------子组件---------------------------------><template>
<div>
<input type="button"
:class="{active:$store.state.isRed}"
value="改变"
@click="$store.state.isRed=!$store.state.isRed">
</div></template><script>
export default {}
</script><style scoped>
.active{ background:red;
}</style>到目前为止,这个示例就被简化了很多?
前面将代码都写到了main.js中了,为了日后便于维护,更好的管理vuex,最好对vuex进行一些调整。
1、在src文件夹根目录创建vuex文件夹,然后在该文件夹内创建store.js文件。然后在文件内引入vue和vuex。
import Vue from 'vue';import Vuex from 'vuex';
2、然后使用Vuex
Vue.use(Vuex );//使用Vuex //创建一个常量对象const state={
isRed:false}//让外部引用vuexexport default new Vuex.Store({//创建vuex中的store对象
state
})3、然后将main.js之前写入的与vuex相关的内容清除掉,引入刚刚创建的store.js文件
import store from '@/vuex/store'
4、在实例化Vue对象时,加入引入的store对象:
new Vue({ el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})5、npm run dev,正常运行!
6、未完,待续!
作者:张培跃
链接:https://www.jianshu.com/p/d109e16d5f9a
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦