目录
1.Vuex 的思维解决,给 <input> 中绑定 value,然后侦听 input 或者 change 事件,在事件回调中调用 action。
2.调用函数
5.具体代码如下:
form.vue
<template>
<div>
<h1>原数据</h1>
<p>{{newarr}}</p>
<!-- 2.把拿过来的数据绑定 属性绑定变量v-bind 当用户输入内容的时候触发一个函数-->
<input type="text" :value="newarr" @input="fun"/>
</div>
</template>
<script>
export default {
computed:{
// 1.把state中的数据拿过来
newarr(){
return this.$store.state.con;
}
},
methods:{
//3.创建函数调用异步的actions, 并且把输入框的内容传递给actions
fun(e){
this.$store.dispatch("actionsfun2",e.target.value);
}
}
}
</script>
<style scoped>
</style>
store.js
import Vue from 'vue';
import Vuex from 'vuex';
// 在vue中使用vuex
Vue.use(Vuex);
// 导出 让外部使用实例化的store对象
export let store=new Vuex.Store({
// 开启严格模式
strict:true,
// 在state里面保存需要保存的数据
state:{
arr:[
{id:1,name:"哈哈",age:12},
{id:2,name:"嘻嘻",age:32},
{id:3,name:"呵呵",age:62},
{id:4,name:"噢噢",age:89}
],
con:"我是默认值"
},
getters:{
// 取出id大于2的数据
// state就是state这个属性
newarr1(state){
var obja=state.arr.filter((v,i)=>{
if(v.id>2){
return v;
}
})
return obja;
},
// 取出id小于等于2的数据
newarr2(state){
var objb=state.arr.filter((v,i)=>{
if(v.id<=2){
return state.arr[i];
}
})
return objb;
}
},
mutations:{
jia(state){
state.arr.forEach((v,i)=>{
v.age++;
})
},
cc(state,payload){
state.arr[3].name=payload;
},
bb(state,payload){
state.arr.push(payload);
},
// 5.创建mutations来进行修改
mutationsfun(state,payload){
state.con=payload;
}
},
actions:{
actionsfun(storeobj){
// 调用mutations中的方法
storeobj.commit("jia");
},
// 4.创建actions进行异步的修改操作
actionsfun2(storeobj,payload){
storeobj.commit("mutationsfun",payload);
}
}
})