什么是Vuex?
uex是一个专门为vue.js设计的集中式状态管理架构。状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态。简单的说就是data中需要共用的属性。
vue项目当中的父子组件的交互是单通道传递,父组件通过props向子组件传递参数,而在子组件当中不不能直接修改接收的参数,而是需要通过自定义事件的方式,例如:
父组件:
<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>
简单说一下vue.sync的作用:
在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。
vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。
想仔细了解移步官方:官方地址
之所以这么麻烦 , 是因为父组件可以通过 props
给子组件传递参数 , 但子组件内却不能直接修改父组件传过来的参数。
这时候 , 使用 vuex
就可以比较方便的解决这种问题了 :
一.引入vuex
1、首先用npm包管理工具,安装vuex
npm install vuex --save
因为这个包在生产环境中也要使用,所以在这里一定要加上 –save
2、新建一个store文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。(为了日后便于维 护,更好的管理vuex)
import Vue from 'vue';
import Vuex from 'vuex';
3、使用我们vuex,引入之后用Vue.use进行引用
Vue.use(Vuex);
4、在main.js 中引入新建的vuex文件
import store from './store/store'
5、在实例化 Vue对象时加入 store 对象 :
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
父组件:
<template>
<div>
<a href="javascript:;" @click="$store.state.show = true">点击</a>
<children ></children>
</div>
</template>
<script>
import children from "@/components/children"
export default {
components: {
children
}
}
</script>
子组件:
<template>
<div>
<span :class="{active:$store.state.show}">颜色改变</span>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
.active{
background:red;
}
</style>
未完待续。。。。。。