在src下新建一个 /store/index.js,内容如下
/*引用vue和vuex*/
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex)
/*设置state参数*/
const state = {
childText2: '',
childText:"",
txtArr:[]
}
const mutations = {
changeChildText(state, str){
state.childText = str;
state.txtArr.push(str)
},
changeChildText2(state, str){
state.childText2 = str;
state.txtArr.push(str)
},
delLast() {
state.txtArr.pop()
}
}
const store = new Vuex.Store({
state: state,
mutations: mutations
})
export default store;
在main.js里面引用
import store from './store/index'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
这样就可以在vue里面使用了:
<template>
<div class="ctn">
<header v-for="item in getArr">
{{item}}
</header>
<slot v-if="getArr.length == 0">暂无信息</slot>
<div>
<input type="text" v-model="txt" placeholder="请输入对话内容">
</div>
<div>
<button @click="changeTxt">甲方发言</button>
<button @click="changeTxt2">乙方发言</button>
<button v-if="getArr.length != 0" @click="delTxt">撤回最新发言</button>
</div>
</div>
</template>
<script>
export default {
data (){
return{
txt:''
}
},
methods:{
changeTxt (){ // 调用/store/index.js里的mutations方法并传参
this.$store.commit("changeChildText", '甲:'+this.txt);
this.txt = ''
},
changeTxt2 (){ //同理
this.$store.commit("changeChildText2", '乙:'+this.txt);
this.txt = ''
},
delTxt(){ //同理
this.$store.commit("delLast")
}
},
computed: {
getTxt () { // 获取 /store/index.js里的state参数
return this.$store.state.childText;
},
getTxt2 () { //同理
return this.$store.state.childText2;
},
getArr () { //同理
return this.$store.state.txtArr;
}
}
}
</script>
<style scoped>
input {
padding: 2px;
}
</style>
网友评论