<!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> vote example</h2>
<hr>
<div id="example-2">
<div v-for="(item, key, index) in this.$store.state.voteitems">
<!-- // right
<label >{{item}},{{item.text}},{{item.value}}</label>
-->
<abc v-bind:item="item" v-bind:key="item.id"></abc>
</div>
</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}],
},
mutations:{
//顯式的更改state裏的數據
changeadd:function(state,a){
var t=myStore.state.voteitems
for(var i=0;i<t.length;i++)
{
if(t[i].text==a){
t[i].value++
}
}
},
changedet:function(state,a){
var t=myStore.state.voteitems
for(var i=0;i<t.length;i++)
{
if(t[i].text==a){
t[i].value--
}
}
},
changeadjust:function(state,option){
var a=option.targ
var type=""
type= option.type
var t=myStore.state.voteitems
for(var i=0;i<t.length;i++)
{
if(t[i].text==a){
if(type=='add'){
t[i].value++
}else{
t[i].value--
}
}
}
},
},
getters:{
},
actions:{
}
});
Vue.component('abc',{
template:`
<div>
<label :name="item.text">{{item.text}} {{item.value}}</label>
<button @click="changeCount('add',$event)" :id="item.text" >add</button>
<button @click="changeCount('det',$event)" :id="item.text" >det</button>
</div>
`,
methods:{
changeCount: function(type,event){
/* ///註釋,測試多參數傳遞
if(type=='add'){
var targ=event.srcElement.getAttribute("id")
this.$store.commit('changeadd',targ)
}else{
var targ=event.srcElement.getAttribute("id")
this.$store.commit('changedet',targ)
}
*/
//測試多參數傳遞 必須寫成對象或者數組再傳入
var targ=event.srcElement.getAttribute("id")
var option={targ,type}
this.$store.commit('changeadjust',option)
},
},
computed: {
abcname:function(){
//return this.$myStore.state.name
//return this.$store.state.name
},
},
props:["item"]
})
new Vue({
el: '#example-2',
data: {
//voteitems:[{text:'A',value:0},{text:'B',value:0},{text:'C',value:0},{text:'D',value:0}],
// voteitems: this.$store.state.voteitems
},
store:myStore,
computed:{
// voteitemss(){
// this.voteitems = this.$store.state.voteitems
// }
}
})
</script>
</body>
</html>