Vuex实现数据共享
<head>
<meta charset="UTF-8">
<!--注意点: 在导入Vuex之前必须先导入Vue-->
<script src="js/vue.js"></script>
<!--导入Vuex-->
<script src="js/vuex.js"></script>
</head>
<body>
<div id="app">
<yeye></yeye>
</div>
<template id="yeye">
<div>
<p>{{this.$store.state.msg}}</p>
<baba></baba>
</div>
</template>
<template id="baba">
<div>
<p>{{this.$store.state.msg}}</p>
<erzi></erzi>
</div>
</template>
<template id="erzi">
<p>{{this.$store.state.msg}}</p>
</template>
<script>
//创建Vuex实例对象
const store = new Vuex.Store({
state:{
msg:'vuex中的共享数据'
}
})
Vue.component('yeye',{
template:'#yeye',
//在祖先组件中添加store的key保存Vue对象,只要组件组件中
//保存了Vuex中state中的数据,其后代组件都可使用
store:store,
components:{
'baba':{
template:'#baba',
components:{
'erzi':{
template:'#erzi'
}
}
}
}
})
let vue = new Vue({
el:'#app',
data:{
}
});
</script>
</body>
Vuex修改数据
在store的实例中通过mutations中定义修改共享数据的方法,执行mutations中定义的方法时, 系统会自动给这些方法传递一个state参数,state中就保存了共享的数据
在组件调用mutations中的方法时,通过methods的this.$store.commit(‘方法名’)的形式调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--导入vue.js文件-->
<script src="js/vue.js"></script>
<script src="js/vuex.js"></script>
</head>
<body>
<div id="app">
<baba></baba>
</div>
<template id="baba">
<div>
<son1></son1>
<son2></son2>
</div>
</template>
<template id="son1">
<div>
<button @click="add" >增加</button>
<button @click="sub">减少</button>
<input type="text" :value="this.$store.state.count">
</div>
</template>
<template id="son2">
<p>{{this.$store.state.count}}</p>
</template>
<script>
//创建Vuex实例对象
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
mAdd(state){
state.count ++;
},
mSub(state){
state.count --;
}
}
})
Vue.component('baba',{
template:'#baba',
//在祖先组件中添加store的key保存Vue对象,只要组件组件中
//保存了Vuex中state中的数据,其后代组件都可使用
store:store,
components:{
'son1':{
template:'#son1',
methods:{
add(){
this.$store.commit('mAdd')
},
sub(){
this.$store.commit('mSub')
}
},
},
'son2':{
template:'#son2'
}
}
})
let vue = new Vue({
el:'#app',
data:{
}
});
</script>
</body>
</html>
Vuex的getters计算属性
在Vuex的实例对象的getters中定义计算属性的方法,如果数据没有更新,则方法只会执行一次,再次读取数据时,读取的是缓存中的值。
<body>
<div id="app">
<baba></baba>
</div>
<template id="baba">
<div>
<p>{{this.$store.getters.format}}</p>
<p>{{this.$store.getters.format}}</p>
<p>{{this.$store.getters.format}}</p>
</div>
</template>
<script>
//创建Vuex实例对象
const store = new Vuex.Store({
state:{
msg:'aaaaa'
},
getters:{
format(state){
console.log('计算属性执行了');
return state.msg+'bbbbb'
}
}
})
Vue.component('baba',{
template:'#baba',
store:store
})
let vue = new Vue({
el:'#app',
data:{
}
});
</script>
</body>