<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> x</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
<!--
<script src="C:\Users\SDSC-XAD\node_modules\vuex\dist\vuex.js" />
<script src="https://unpkg.com/[email protected]" ></script>
-->
<script src="https://unpkg.com/[email protected]" ></script>
</head>
<body>
<h1>vuex</h1>
<h2> vuex example</h2>
<hr>
<div id="example-2">
<div>
輔助函數 mapState、mapGetters、mapMutations、mapActions
可以在組件中做對象映射
</div>
<counter></counter>
</div>
<script type="text/javascript">
var myStore = new Vuex.Store({
state:{
voteitems:[{text:'A',value:0},{text:'B',value:0},{text:'C',value:0},{text:'D',value:0}],
count:0,
count2:1,
count3:2,
str01:"str01",
name:'moduleA',
},
mutations:{
deIncrement:function(state,a){
state.count3--
},
increment:function(state,a){
state.count3++
},
changeadjust:function(state,option){
},
},
getters:{
str01: state => {
return state.str01
},
str02: state => {
return state.str01
}
},
actions:{
addAction:function(state,a){
//可以直接修改
//this.myStore.state.count3++
// async / await 同步和異步
//或者提交給mutations
this.myStore.commit('increment', 10)
}
}
})
Vue.component('counter', {
template: `<div>{{ count }} {{countPlusLocalState}} {{anotherState}} {{str01}} {{str02}}
<button @click="addHandle">add</button>
<button @click="deHandle">de</button>
</div>`,
data: function(){
return {localCount:20}
},
// computed 1
/*
computed: {
count () {
return this.$store.state.count
}
}
*/
// computed 2
//computed: mapState 改爲 computed: Vuex.mapState ,這樣就不會報錯了
// computed: Vuex.mapState({
// count:'count2'
//})
// computed 3
/*
computed:Vuex.mapState({
// count:state=>state.count2, //理解爲傳入state對象,修改state.count屬性
// count: state => state.count2,
count: 'count3',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
*/
//// computed 4
computed:{
// … 三個點,在框架語言裏,就是傳對象
...Vuex.mapState({
// count:state=>state.count2, //理解爲傳入state對象,修改state.count屬性
// count: state => state.count2,
count: 'count3',
countPlusLocalState (state) {
return state.count + this.localCount
}
}),
// 使用對象展開運算符將 getter 混入 computed 對象中,同時也可以起別名,別名暫時沒調通
...Vuex.mapGetters([
'str01',
'str02',
// str03:'str01',
]),
// 可以使用外部方法
...Vuex.mapState({
anotherState (state) {
return outsidefunction()
}
})
},
methods: {
// 分發給store中的方法或者action
...Vuex.mapActions({
addHandle: 'addAction'
}),
// 輔助函數不能直接傳值,可以在方法體內傳值
...Vuex.mapMutations({
deHandle: 'deIncrement'
})
}
})
function outsidefunction(){
return 100;
}
function localincr(){
this.myStore.state.count3++
}
new Vue({
el: '#example-2',
data: {
},
store:myStore,
computed:{
}
})
</script>
</body>
</html>