时间:2022-07-21 11:10:30 | 栏目:vue | 点击:次
// main.js中,把store注册在根实例下,可使用this.$stroe.state直接取值 export default { computed: { testNum() { return this.$store.state.testNum; } } };
import { mapState } from "vuex";export default { data() { return { localNum: 1 }; }, computed: { ...mapState({ // 箭头函数使代码更简练 testNum1: state => state.testNum1, // 传字符参数'testNum2' 等价于 'state => state.testNum2' testNum2: "testNum2", // 组件的局部变量与Vuex变量相加 testNum3(state) { return state.testNum1 + this.localNum; } }), ...mapState([ // 映射this.testNum3为store.state.testNum3 "testNum3" ]) } };
import { mapState } from "vuex"; export default { computed: { ...mapState({ // 箭头函数使代码更简练 testNum1: state => state.moduleA.testNum1 }), // 第一个参数是namespace命名空间,填上对应的module名称即可 ...mapState("moduleA", { testNum2: state => state.testNum2, testNum3: "testNum3" }), ...mapState("moduleA",[ "testNum4" ]) } };
直接访问 <h1>姓名:{{$store.state.msg}}</h1>
将想要用到的全局state数据,防止到组件的computed内部使用,v-model的内容将其获取和设置分开即可
<h1>姓名:{{msg}}</h1> <h1>年龄:{{age}}</h1> <h1>数字:{{num}}</h1> <input type="text" v-model="num"> computed: { age:function(){ //msg也相同,就没写 return this.$store.state.age }, num:{ get:function(){ return this.$store.state.num; }, set:function(num){ //数据双向绑定 this.$store.commit('setNum',num) } } },
<h1>姓名:{{msg}}</h1> <h1>年龄:{{age}}</h1> <h1>数字:{{num}}</h1> <input type="text" :value="num" @input="changeVal" > import { mapState } from 'vuex' //需要引入mapState computed:mapState(['age','msg','num']), methods: { changeVal(e){ //设置值 return this.$store.commit('setNum',e.target.value) } },
<h1>姓名:{{msg}}</h1> <h1>年龄:{{age}}</h1> <h1>数字:{{num}}</h1> import { mapState } from 'vuex' //需要引入mapState computed:mapState({ msg:'msg', num:'num', // age:(state)=>state.age, //不需要大括号的时候,就不需要用 return 返回值 age:(state)=>{ return state.age}, })
<h1>姓名:{{msg}}</h1> <h1>年龄:{{age}}</h1> <h1>数字:{{num}}</h1> import { mapState } from 'vuex' let objMapState=mapState({ msg:'msg', num:'num', // age:(state)=>state.age, age:function(state){ return this.greenColor+state.age}, }) data() { return { greenColor:'blue' } }, computed:{ ...mapState(objMapState) }