老师,我在Home.vue中里边加入vuex的mapState,映射了city属性,但是页面报错了

来源:8-12 Vue项目城市选择页 - 使用keep-alive优化网页性能

Keily

2021-01-01

报错图片描述
代码如下:

<template>
  <div>
    <home-header></home-header><!--:city="city"-->
    <home-swiper :list="swiperList"></home-swiper>
    <home-icons :list="iconList"></home-icons>
    <home-recommend :list="recommendList"></home-recommend>
    <home-weekend :list="weekendList"></home-weekend>
  </div>

</template>

<script>
import HomeHeader from './components/Header.vue'
import HomeSwiper from './components/Swiper.vue'
import HomeIcons from './components/Icons.vue'
import HomeRecommend from './components/Recomment.vue'
import HomeWeekend from './components/Weekend.vue'
import axios from 'axios'
import {
  mapState
} from 'vuex'
export default{
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  computed: {
    ...mapState(['city'])
   
  },
  data () {
    return {
      // city: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  methods: {
    getHomeInfo: function () {
      axios.get('/api/index.json?city=' + this.city)
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      // console.log('res:' + JSON.stringify(res))
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.city = data.city
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    console.log('mounted')
    this.getHomeInfo()
  },
  activated () {
    console.log('activated')
  }
}
</script>

<style scoped>

</style>
写回答

2回答

Keily

提问者

2021-01-01

我在换了种写法:

computed: {
    ...mapState({
      'cityFromStore': 'city' // 将vuex中的state中city属性映射到 计算属性city中
    }),
    city: {
      get () {
        return this.cityFromStore
      },
      set (newName) {
        return newName
      }
    }
  },


1
0

Keily

提问者

2021-01-01

后来我换了个写法了,直接使用this.$store.state.city属性了;

1
1
Dell
这块用mapState,如果你给city 值,不能直接改,要用set,你代码里this.city = data.city 这块有问题
2021-01-02
共1条回复

Vue2.5-2.6-3.0开发去哪儿网App 零基础入门到实战

课程紧跟Vue3版本迭代,企业主流版本Vue2+Vue3全掌握

10675 学习 · 8191 问题

查看课程