【问题标题】:Vue: How to use store with component?Vue:如何将 store 与组件一起使用?
【发布时间】:2017-01-26 01:15:37
【问题描述】:

//存储

export default {
  state: {
    aboutModels: []
  },
  actions: {
    findBy: ({commit}, about)=> {
      //do getModels
      var aboutModels = [{name: 'About'}] //Vue.resource('/abouts').get(about)
      commit('setModels', aboutModels)
    }
  },
  getters: {
    getModels(state){
      return state.aboutModels
    }
  },
  mutations: {
    setModels: (state, aboutModels)=> {
      state.aboutModels = aboutModels
    }
  }
}

//组件

import {mapActions, mapGetters} from "vuex";

export default {
  name: 'About',
  template: require('./about.template'),
  style: require('./about.style'),
  created () {
    document.title = 'About'
    this.findBy()
  },
  computed: mapGetters({
    abouts: 'getModels'
  }),
  methods: mapActions({
    findBy: 'findBy'
  })
}

//查看

<div class="about" v-for="about in abouts">{{about.name}}</div>

//错误

vue.js:2532[Vue warn]: Cannot use v-for on stateful component root element because it renders multiple elements:
<div class="about" v-for="about in abouts">{{about.name}}</div>

vue.js:2532[Vue warn]: Multiple root nodes returned from render function. Render function should return a single root node. (found in component <About>)

【问题讨论】:

    标签: vue.js vuejs2 vue-component vue-router vuex


    【解决方案1】:

    您正在正确映射您的 Vuex 状态获取器和操作。正如您的错误消息所述,您的问题是其他问题...

    在您的组件模板中,您不能在根元素上使用v-for 指令。例如,这是不允许的,因为您的组件可以有多个根元素:

    <template>
       <div class="about" v-for="about in abouts">{{about.name}}</div>
    </template>
    

    改为这样做:

    <template>
       <div>
          <div class="about" v-for="about in abouts">{{about.name}}</div>
       </div>
    </template>
    

    ** *修复模板标签中的错字**

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2020-05-22
      • 2017-09-15
      • 2021-09-06
      • 1970-01-01
      • 2020-08-04
      • 2019-09-20
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多