Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: How to use store with component?

//store

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
    }
  }
}

//component

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'
  })
}

//view

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

//error

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>)
like image 589
Dreampie Avatar asked Sep 18 '16 06:09

Dreampie


1 Answers

You are mapping your Vuex state getters and action correctly. Your problem is something else as your error message states...

In your component template you can not use v-for directive on a root element. For example this is not allowed because your component can have multiple root elements:

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

instead do it this way:

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

** *fixed typo in template tag **

like image 132
Primoz Rome Avatar answered Oct 07 '22 23:10

Primoz Rome