programing

Vue: 컴포넌트와 함께 스토어를 사용하는 방법

prostudy 2022. 5. 29. 09:20
반응형

Vue: 컴포넌트와 함께 스토어를 사용하는 방법

//스토어

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

Vuex 상태 getter 및 작업을 올바르게 매핑하고 있습니다.에러 메세지에 기재되어 있듯이, 문제는 다른 것입니다.

컴포넌트 템플릿에서는 사용할 수 없습니다.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>

** *템플릿 태그에 오타가 있습니다**

언급URL : https://stackoverflow.com/questions/39554692/vue-how-to-use-store-with-component

반응형